Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)
Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
23
akode-rs/ext/extension-api/tests/capabilities.rs
Normal file
23
akode-rs/ext/extension-api/tests/capabilities.rs
Normal file
@@ -0,0 +1,23 @@
|
||||
use akode_extension_api::NoopResponseItemInjector;
|
||||
use akode_extension_api::ResponseItemInjector;
|
||||
use akode_protocol::models::ContentItem;
|
||||
use akode_protocol::models::ResponseInputItem;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn noop_response_item_injector_returns_original_items() {
|
||||
let items = vec![ResponseInputItem::Message {
|
||||
role: "user".to_string(),
|
||||
content: vec![ContentItem::InputText {
|
||||
text: "keep this input".to_string(),
|
||||
}],
|
||||
phase: None,
|
||||
}];
|
||||
|
||||
let returned_items = NoopResponseItemInjector
|
||||
.inject_response_items(items.clone())
|
||||
.await
|
||||
.expect_err("noop injector should reject same-turn injection");
|
||||
|
||||
assert_eq!(returned_items, items);
|
||||
}
|
||||
486
akode-rs/ext/extension-api/tests/registry.rs
Normal file
486
akode-rs/ext/extension-api/tests/registry.rs
Normal file
@@ -0,0 +1,486 @@
|
||||
#![allow(clippy::expect_used)]
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use akode_extension_api::ApprovalReviewContributor;
|
||||
use akode_extension_api::ConfigContributor;
|
||||
use akode_extension_api::ContentItemKind;
|
||||
use akode_extension_api::ContextContributor;
|
||||
use akode_extension_api::ContextualUserFragment;
|
||||
use akode_extension_api::ConversationHistorySnapshot;
|
||||
use akode_extension_api::ExtensionData;
|
||||
use akode_extension_api::ExtensionDataInit;
|
||||
use akode_extension_api::ExtensionEventSink;
|
||||
use akode_extension_api::ExtensionFuture;
|
||||
use akode_extension_api::ExtensionMetrics;
|
||||
use akode_extension_api::ExtensionRegistryBuilder;
|
||||
use akode_extension_api::ExtensionWarning;
|
||||
use akode_extension_api::McpServerContributionContext;
|
||||
use akode_extension_api::PromptFragment;
|
||||
use akode_extension_api::ResponseItem;
|
||||
use akode_extension_api::SkillInvocationContributor;
|
||||
use akode_extension_api::ThreadLifecycleContributor;
|
||||
use akode_extension_api::TokenUsageContributor;
|
||||
use akode_extension_api::ToolCall;
|
||||
use akode_extension_api::ToolContributor;
|
||||
use akode_extension_api::ToolExecutor;
|
||||
use akode_extension_api::ToolLifecycleContributor;
|
||||
use akode_extension_api::TurnContextContributionInput;
|
||||
use akode_extension_api::TurnInputContext;
|
||||
use akode_extension_api::TurnInputContributor;
|
||||
use akode_extension_api::TurnItemContributor;
|
||||
use akode_extension_api::TurnLifecycleContributor;
|
||||
use akode_protocol::items::HookPromptItem;
|
||||
use akode_protocol::items::TurnItem;
|
||||
use akode_protocol::protocol::EnvironmentConfigState;
|
||||
use akode_protocol::protocol::Event;
|
||||
use akode_protocol::protocol::EventMsg;
|
||||
use akode_protocol::protocol::SessionSource;
|
||||
use akode_protocol::protocol::SubAgentSource;
|
||||
use akode_protocol::protocol::TurnEnvironmentRequest;
|
||||
use akode_protocol::protocol::TurnEnvironmentSelection;
|
||||
use akode_protocol::protocol::WarningEvent;
|
||||
use akode_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
struct AllContributors;
|
||||
|
||||
#[test]
|
||||
fn mcp_contribution_context_identifies_the_running_thread() {
|
||||
let config = ();
|
||||
let thread_init = ExtensionDataInit::new();
|
||||
let thread_store = ExtensionData::new("child-thread");
|
||||
let session_source = SessionSource::SubAgent(SubAgentSource::Review);
|
||||
|
||||
let thread_context = McpServerContributionContext::for_step(
|
||||
&config,
|
||||
&thread_init,
|
||||
&thread_store,
|
||||
"codex_work_cca",
|
||||
&[],
|
||||
/*executor_capability_discovery*/ None,
|
||||
/*executor_capability_discovery_v2*/ None,
|
||||
)
|
||||
.with_session_source(&session_source);
|
||||
|
||||
assert_eq!(thread_context.session_source(), Some(&session_source));
|
||||
assert_eq!(
|
||||
McpServerContributionContext::global(&config).session_source(),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_context_preserves_selected_executor_order_and_unavailability() {
|
||||
let config = ();
|
||||
let environments = vec![
|
||||
TurnEnvironmentSelection::new(
|
||||
TurnEnvironmentRequest {
|
||||
environment_id: "starting-primary".to_owned(),
|
||||
cwd: PathUri::parse("file:///workspace").expect("workspace URI"),
|
||||
workspace_roots: Vec::new(),
|
||||
config: EnvironmentConfigState::Pending,
|
||||
},
|
||||
&[],
|
||||
),
|
||||
TurnEnvironmentSelection::new(
|
||||
TurnEnvironmentRequest {
|
||||
environment_id: "ready-secondary".to_owned(),
|
||||
cwd: PathUri::parse("file:///other").expect("workspace URI"),
|
||||
workspace_roots: Vec::new(),
|
||||
config: EnvironmentConfigState::FromThread,
|
||||
},
|
||||
&[],
|
||||
),
|
||||
];
|
||||
let context = McpServerContributionContext::global(&config);
|
||||
assert_eq!(context.selected_environments(), None);
|
||||
assert_eq!(
|
||||
context
|
||||
.with_selected_environments(&[])
|
||||
.selected_environments(),
|
||||
Some([].as_slice())
|
||||
);
|
||||
assert_eq!(
|
||||
context
|
||||
.with_selected_environments(&environments)
|
||||
.selected_environments(),
|
||||
Some(environments.as_slice())
|
||||
);
|
||||
}
|
||||
|
||||
impl ContextContributor for AllContributors {
|
||||
fn contribute_thread_context<'a>(
|
||||
&'a self,
|
||||
_session_store: &'a ExtensionData,
|
||||
_thread_store: &'a ExtensionData,
|
||||
) -> ExtensionFuture<'a, Vec<PromptFragment>> {
|
||||
Box::pin(std::future::ready(Vec::new()))
|
||||
}
|
||||
}
|
||||
|
||||
impl ThreadLifecycleContributor<()> for AllContributors {}
|
||||
|
||||
impl TurnLifecycleContributor for AllContributors {}
|
||||
|
||||
impl ConfigContributor<()> for AllContributors {}
|
||||
|
||||
impl TokenUsageContributor for AllContributors {}
|
||||
|
||||
impl SkillInvocationContributor for AllContributors {}
|
||||
|
||||
struct ExecutorOnlySkillContributor;
|
||||
|
||||
impl SkillInvocationContributor for ExecutorOnlySkillContributor {
|
||||
fn requires_host_skill_discovery(&self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_skill_discovery_preserves_legacy_and_host_contributor_behavior() {
|
||||
assert!(
|
||||
ExtensionRegistryBuilder::<()>::new()
|
||||
.build()
|
||||
.requires_host_skill_discovery()
|
||||
);
|
||||
|
||||
let mut executor_only = ExtensionRegistryBuilder::<()>::new();
|
||||
executor_only.skill_invocation_contributor(Arc::new(ExecutorOnlySkillContributor));
|
||||
assert!(!executor_only.build().requires_host_skill_discovery());
|
||||
|
||||
let mut mixed = ExtensionRegistryBuilder::<()>::new();
|
||||
mixed.skill_invocation_contributor(Arc::new(ExecutorOnlySkillContributor));
|
||||
mixed.skill_invocation_contributor(Arc::new(AllContributors));
|
||||
assert!(mixed.build().requires_host_skill_discovery());
|
||||
}
|
||||
|
||||
impl TurnInputContributor for AllContributors {
|
||||
fn contribute<'a>(
|
||||
&'a self,
|
||||
input: TurnInputContext<'a>,
|
||||
_extension_metrics: Option<Arc<dyn ExtensionMetrics>>,
|
||||
_session_store: &'a ExtensionData,
|
||||
_thread_store: &'a ExtensionData,
|
||||
_turn_store: &'a ExtensionData,
|
||||
) -> ExtensionFuture<'a, Vec<Box<dyn ContextualUserFragment + Send>>> {
|
||||
Box::pin(async move {
|
||||
let _self = self;
|
||||
let _input = input;
|
||||
Vec::new()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolContributor for AllContributors {
|
||||
fn tools(
|
||||
&self,
|
||||
_session_store: &ExtensionData,
|
||||
_thread_store: &ExtensionData,
|
||||
) -> Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolLifecycleContributor for AllContributors {}
|
||||
|
||||
impl TurnItemContributor for AllContributors {
|
||||
fn contribute<'a>(
|
||||
&'a self,
|
||||
_thread_store: &'a ExtensionData,
|
||||
_turn_store: &'a ExtensionData,
|
||||
_item: &'a mut TurnItem,
|
||||
) -> ExtensionFuture<'a, Result<(), String>> {
|
||||
Box::pin(async move {
|
||||
let _self = self;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ApprovalReviewContributor for AllContributors {
|
||||
fn decide<'a>(
|
||||
&'a self,
|
||||
_input: &'a akode_extension_api::ApprovalDecisionInput<'_>,
|
||||
) -> ExtensionFuture<'a, Option<akode_extension_api::ApprovalDecision>> {
|
||||
Box::pin(async { Some(akode_extension_api::ApprovalDecision::AskUser) })
|
||||
}
|
||||
}
|
||||
|
||||
impl akode_extension_api::SynchronousApprovalReviewer for AllContributors {
|
||||
fn review<'a>(
|
||||
&'a self,
|
||||
_reason: akode_protocol::approvals::GuardianReviewReason,
|
||||
_async_approval: Option<akode_extension_api::ExtensionFuture<'a, ()>>,
|
||||
) -> ExtensionFuture<'a, Option<akode_protocol::protocol::ReviewDecision>> {
|
||||
Box::pin(std::future::ready(Some(
|
||||
akode_protocol::protocol::ReviewDecision::Approved,
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn build_round_trips_every_contributor_category() {
|
||||
let contributor = Arc::new(AllContributors);
|
||||
let mut builder = ExtensionRegistryBuilder::<()>::new();
|
||||
builder.thread_lifecycle_contributor(contributor.clone());
|
||||
builder.turn_lifecycle_contributor(contributor.clone());
|
||||
builder.config_contributor(contributor.clone());
|
||||
builder.token_usage_contributor(contributor.clone());
|
||||
builder.skill_invocation_contributor(contributor.clone());
|
||||
builder.prompt_contributor(contributor.clone());
|
||||
builder.turn_input_contributor(contributor.clone());
|
||||
builder.tool_contributor(contributor.clone());
|
||||
builder.tool_lifecycle_contributor(contributor.clone());
|
||||
builder.turn_item_contributor(contributor.clone());
|
||||
builder.approval_review_contributor(contributor);
|
||||
let registry = builder.build();
|
||||
|
||||
assert_eq!(registry.thread_lifecycle_contributors().len(), 1);
|
||||
assert_eq!(registry.turn_lifecycle_contributors().len(), 1);
|
||||
assert_eq!(registry.config_contributors().len(), 1);
|
||||
assert_eq!(registry.token_usage_contributors().len(), 1);
|
||||
assert_eq!(registry.skill_invocation_contributors().len(), 1);
|
||||
assert_eq!(registry.context_contributors().len(), 1);
|
||||
assert_eq!(registry.turn_input_contributors().len(), 1);
|
||||
assert_eq!(registry.tool_contributors().len(), 1);
|
||||
assert_eq!(registry.tool_lifecycle_contributors().len(), 1);
|
||||
assert_eq!(registry.turn_item_contributors().len(), 1);
|
||||
let thread_store = ExtensionData::new("thread");
|
||||
let input = akode_extension_api::ApprovalDecisionInput {
|
||||
serving_assessment: None,
|
||||
permissions: Some(&Default::default()),
|
||||
approval_id: "approval-1",
|
||||
tool_call_id: None,
|
||||
action: &serde_json::Value::Null,
|
||||
thread_id: akode_protocol::ThreadId::new(),
|
||||
thread_store: &thread_store,
|
||||
turn_store: &thread_store,
|
||||
category: akode_protocol::openai_models::GuardianScope::Shell,
|
||||
approval_policy: akode_protocol::protocol::AskForApproval::OnRequest,
|
||||
approvals_reviewer: akode_protocol::config_types::ApprovalsReviewer::AutoReview,
|
||||
require_guardian: false,
|
||||
require_fresh_review: false,
|
||||
full_access: false,
|
||||
metrics: None,
|
||||
synchronous_reviewer: &AllContributors,
|
||||
};
|
||||
assert_eq!(
|
||||
registry.decide_approval(&input).await,
|
||||
Some(akode_extension_api::ApprovalDecision::AskUser)
|
||||
);
|
||||
}
|
||||
|
||||
impl ConversationHistorySnapshot for AllContributors {
|
||||
fn history_version(&self) -> u64 {
|
||||
0
|
||||
}
|
||||
|
||||
fn user_message_revision(&self) -> u64 {
|
||||
0
|
||||
}
|
||||
|
||||
fn items(&self) -> Box<dyn Iterator<Item = &ResponseItem> + Send + '_> {
|
||||
Box::new(std::iter::empty())
|
||||
}
|
||||
}
|
||||
|
||||
struct NamedContextContributor(&'static str);
|
||||
|
||||
impl ContextContributor for NamedContextContributor {
|
||||
fn contribute_thread_context<'a>(
|
||||
&'a self,
|
||||
_session_store: &'a ExtensionData,
|
||||
_thread_store: &'a ExtensionData,
|
||||
) -> ExtensionFuture<'a, Vec<PromptFragment>> {
|
||||
Box::pin(std::future::ready(vec![PromptFragment::developer_policy(
|
||||
self.0,
|
||||
ContentItemKind("test.thread_context".to_string()),
|
||||
)]))
|
||||
}
|
||||
}
|
||||
|
||||
struct NamedTurnContextContributor(&'static str);
|
||||
|
||||
impl ContextContributor for NamedTurnContextContributor {
|
||||
fn contribute_turn_context<'a>(
|
||||
&'a self,
|
||||
_input: TurnContextContributionInput<'a>,
|
||||
) -> ExtensionFuture<'a, Vec<PromptFragment>> {
|
||||
Box::pin(std::future::ready(vec![
|
||||
PromptFragment::developer_capability(
|
||||
self.0,
|
||||
ContentItemKind("test.turn_context".to_string()),
|
||||
),
|
||||
]))
|
||||
}
|
||||
}
|
||||
|
||||
struct RecordingTurnItemContributor {
|
||||
name: &'static str,
|
||||
calls: Arc<Mutex<Vec<&'static str>>>,
|
||||
}
|
||||
|
||||
impl TurnItemContributor for RecordingTurnItemContributor {
|
||||
fn contribute<'a>(
|
||||
&'a self,
|
||||
_thread_store: &'a ExtensionData,
|
||||
_turn_store: &'a ExtensionData,
|
||||
_item: &'a mut TurnItem,
|
||||
) -> ExtensionFuture<'a, Result<(), String>> {
|
||||
Box::pin(async move {
|
||||
self.calls
|
||||
.lock()
|
||||
.expect("turn item calls lock should not be poisoned")
|
||||
.push(self.name);
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn contributors_preserve_registration_order() {
|
||||
let turn_item_calls = Arc::new(Mutex::new(Vec::new()));
|
||||
let mut builder = ExtensionRegistryBuilder::<()>::new();
|
||||
builder.prompt_contributor(Arc::new(NamedContextContributor("first")));
|
||||
builder.prompt_contributor(Arc::new(NamedContextContributor("second")));
|
||||
builder.prompt_contributor(Arc::new(NamedTurnContextContributor("turn-first")));
|
||||
builder.prompt_contributor(Arc::new(NamedTurnContextContributor("turn-second")));
|
||||
for name in ["first", "second"] {
|
||||
builder.turn_item_contributor(Arc::new(RecordingTurnItemContributor {
|
||||
name,
|
||||
calls: Arc::clone(&turn_item_calls),
|
||||
}));
|
||||
}
|
||||
let registry = builder.build();
|
||||
let session_store = ExtensionData::new("session");
|
||||
let thread_store = ExtensionData::new("thread");
|
||||
let turn_store = ExtensionData::new("turn");
|
||||
|
||||
let mut fragments = Vec::new();
|
||||
for contributor in registry.context_contributors() {
|
||||
fragments.extend(
|
||||
contributor
|
||||
.contribute_thread_context(&session_store, &thread_store)
|
||||
.await,
|
||||
);
|
||||
}
|
||||
for contributor in registry.context_contributors() {
|
||||
fragments.extend(
|
||||
contributor
|
||||
.contribute_turn_context(TurnContextContributionInput {
|
||||
thread_id: akode_protocol::ThreadId::default(),
|
||||
turn_id: turn_store.level_id(),
|
||||
session_store: &session_store,
|
||||
thread_store: &thread_store,
|
||||
turn_store: &turn_store,
|
||||
model_context_window: Some(123),
|
||||
})
|
||||
.await,
|
||||
);
|
||||
}
|
||||
let mut item = TurnItem::HookPrompt(HookPromptItem {
|
||||
id: "item".to_string(),
|
||||
fragments: Vec::new(),
|
||||
});
|
||||
for contributor in registry.turn_item_contributors() {
|
||||
contributor
|
||||
.contribute(&thread_store, &turn_store, &mut item)
|
||||
.await
|
||||
.expect("turn item contribution should succeed");
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
fragments,
|
||||
vec![
|
||||
PromptFragment::developer_policy(
|
||||
"first",
|
||||
ContentItemKind("test.thread_context".to_string()),
|
||||
),
|
||||
PromptFragment::developer_policy(
|
||||
"second",
|
||||
ContentItemKind("test.thread_context".to_string()),
|
||||
),
|
||||
PromptFragment::developer_capability(
|
||||
"turn-first",
|
||||
ContentItemKind("test.turn_context".to_string()),
|
||||
),
|
||||
PromptFragment::developer_capability(
|
||||
"turn-second",
|
||||
ContentItemKind("test.turn_context".to_string()),
|
||||
),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
turn_item_calls
|
||||
.lock()
|
||||
.expect("turn item calls lock")
|
||||
.as_slice(),
|
||||
["first", "second"]
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct RecordingEventSink {
|
||||
events: Mutex<Vec<(String, String)>>,
|
||||
}
|
||||
|
||||
impl ExtensionEventSink for RecordingEventSink {
|
||||
fn emit(&self, event: Event) {
|
||||
let EventMsg::Warning(warning) = event.msg else {
|
||||
panic!("test sink only accepts warning events");
|
||||
};
|
||||
self.events
|
||||
.lock()
|
||||
.expect("recording event sink lock should not be poisoned")
|
||||
.push((event.id, warning.message));
|
||||
}
|
||||
|
||||
fn emit_warning(&self, warning: ExtensionWarning) {
|
||||
self.events
|
||||
.lock()
|
||||
.expect("recording event sink lock should not be poisoned")
|
||||
.push((warning.thread_id, warning.message));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_event_sink_survives_registry_build() {
|
||||
let sink = Arc::new(RecordingEventSink::default());
|
||||
let builder = ExtensionRegistryBuilder::<()>::with_event_sink(sink.clone());
|
||||
|
||||
builder
|
||||
.event_sink()
|
||||
.emit(warning_event("builder", "before"));
|
||||
let registry = builder.build();
|
||||
registry
|
||||
.event_sink()
|
||||
.emit(warning_event("registry", "after"));
|
||||
registry.event_sink().emit_warning(ExtensionWarning {
|
||||
thread_id: "thread".to_string(),
|
||||
turn_id: Some("turn".to_string()),
|
||||
message: "warning".to_string(),
|
||||
});
|
||||
|
||||
assert_eq!(
|
||||
sink.events
|
||||
.lock()
|
||||
.expect("recording event sink lock")
|
||||
.as_slice(),
|
||||
[
|
||||
("builder".to_string(), "before".to_string()),
|
||||
("registry".to_string(), "after".to_string()),
|
||||
("thread".to_string(), "warning".to_string()),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
fn warning_event(id: &str, message: &str) -> Event {
|
||||
Event {
|
||||
id: id.to_string(),
|
||||
msg: EventMsg::Warning(WarningEvent {
|
||||
message: message.to_string(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
140
akode-rs/ext/extension-api/tests/state.rs
Normal file
140
akode-rs/ext/extension-api/tests/state.rs
Normal file
@@ -0,0 +1,140 @@
|
||||
use std::panic::AssertUnwindSafe;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Barrier;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use akode_extension_api::ExtensionData;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn typed_values_can_be_inserted_replaced_and_removed() {
|
||||
let data = ExtensionData::new("thread-1");
|
||||
|
||||
assert_eq!(data.insert(/*value*/ 41_u64), None);
|
||||
assert_eq!(data.insert("alpha".to_string()), None);
|
||||
assert_eq!(data.get::<u64>().as_deref(), Some(&41));
|
||||
assert_eq!(
|
||||
data.get::<String>().map(|value| value.as_str().to_string()),
|
||||
Some("alpha".to_string())
|
||||
);
|
||||
|
||||
assert_eq!(data.insert(/*value*/ 42_u64).as_deref(), Some(&41));
|
||||
assert_eq!(data.get::<u64>().as_deref(), Some(&42));
|
||||
assert_eq!(
|
||||
data.remove::<String>()
|
||||
.map(|value| value.as_str().to_string()),
|
||||
Some("alpha".to_string())
|
||||
);
|
||||
assert_eq!(data.get::<String>(), None);
|
||||
assert_eq!(data.get::<u64>().as_deref(), Some(&42));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conditional_insert_keeps_the_newest_concurrent_value() {
|
||||
const CALLER_COUNT: u64 = 16;
|
||||
|
||||
let data = Arc::new(ExtensionData::new("thread-1"));
|
||||
let callers_ready = Arc::new(Barrier::new(CALLER_COUNT as usize));
|
||||
let handles = (0..CALLER_COUNT)
|
||||
.map(|value| {
|
||||
let data = Arc::clone(&data);
|
||||
let callers_ready = Arc::clone(&callers_ready);
|
||||
std::thread::spawn(move || {
|
||||
callers_ready.wait();
|
||||
data.insert_if(value, |existing| {
|
||||
existing.is_none_or(|existing| value > *existing)
|
||||
});
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
for handle in handles {
|
||||
handle.join().expect("insertion thread should succeed");
|
||||
}
|
||||
|
||||
assert_eq!(data.get::<u64>().as_deref(), Some(&(CALLER_COUNT - 1)));
|
||||
assert!(!data.insert_if(/*value*/ 0_u64, |existing| {
|
||||
existing.is_none_or(|existing| *existing == 0)
|
||||
}));
|
||||
assert_eq!(data.get::<u64>().as_deref(), Some(&(CALLER_COUNT - 1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_or_init_initializes_once_and_returns_shared_value() {
|
||||
const CALLER_COUNT: usize = 8;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct SharedValue(usize);
|
||||
|
||||
let data = Arc::new(ExtensionData::new("session"));
|
||||
let callers_started = Arc::new(AtomicUsize::new(0));
|
||||
let initialization_count = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
let handles: [_; CALLER_COUNT] = std::array::from_fn(|_| {
|
||||
let data = Arc::clone(&data);
|
||||
let callers_started = Arc::clone(&callers_started);
|
||||
let initialization_count = Arc::clone(&initialization_count);
|
||||
std::thread::spawn(move || {
|
||||
callers_started.fetch_add(1, Ordering::SeqCst);
|
||||
data.get_or_init(|| {
|
||||
initialization_count.fetch_add(1, Ordering::SeqCst);
|
||||
// Keep the first initializer active until every worker has attempted
|
||||
// get_or_init, forcing callers to overlap on the same missing entry.
|
||||
while callers_started.load(Ordering::SeqCst) < CALLER_COUNT {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
SharedValue(7)
|
||||
})
|
||||
})
|
||||
});
|
||||
let values = handles
|
||||
.into_iter()
|
||||
.map(|handle| handle.join().expect("initializer thread should succeed"))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
assert_eq!(initialization_count.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(
|
||||
values.iter().map(Arc::as_ref).collect::<Vec<_>>(),
|
||||
vec![&SharedValue(7); CALLER_COUNT]
|
||||
);
|
||||
assert!(
|
||||
values
|
||||
.iter()
|
||||
.skip(1)
|
||||
.all(|value| Arc::ptr_eq(&values[0], value))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stores_are_isolated_and_preserve_level_id() {
|
||||
let session_data = ExtensionData::new("root-1");
|
||||
let thread_data = ExtensionData::new("root-1");
|
||||
|
||||
session_data.insert(/*value*/ 17_u32);
|
||||
thread_data.insert("thread value".to_string());
|
||||
|
||||
assert_eq!(session_data.level_id(), "root-1");
|
||||
assert_eq!(thread_data.level_id(), "root-1");
|
||||
assert_eq!(session_data.get::<u32>().as_deref(), Some(&17));
|
||||
assert_eq!(session_data.get::<String>(), None);
|
||||
assert_eq!(thread_data.get::<u32>(), None);
|
||||
assert_eq!(
|
||||
thread_data
|
||||
.get::<String>()
|
||||
.map(|value| value.as_str().to_string()),
|
||||
Some("thread value".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn store_remains_usable_after_panicking_initializer() {
|
||||
let data = ExtensionData::new("turn-1");
|
||||
|
||||
let result = std::panic::catch_unwind(AssertUnwindSafe(|| {
|
||||
data.get_or_init::<u64>(|| panic!("initializer failed"));
|
||||
}));
|
||||
|
||||
assert!(result.is_err());
|
||||
assert_eq!(*data.get_or_init(|| 99_u64), 99);
|
||||
}
|
||||
Reference in New Issue
Block a user