chore: remove production code only reachable from tests (#12504)
This commit is contained in:
@@ -76,43 +76,6 @@ const UI_RESOURCES: &[UIResourceDef] = &[
|
||||
},
|
||||
];
|
||||
|
||||
/// Validates that the data parameter is a proper JSON value and not a string
|
||||
fn validate_data_param(params: &Value, allow_array: bool) -> Result<Value, ErrorData> {
|
||||
let data_value = params.get("data").ok_or_else(|| {
|
||||
ErrorData::new(
|
||||
ErrorCode::INVALID_PARAMS,
|
||||
"Missing 'data' parameter".to_string(),
|
||||
None,
|
||||
)
|
||||
})?;
|
||||
|
||||
if data_value.is_string() {
|
||||
return Err(ErrorData::new(
|
||||
ErrorCode::INVALID_PARAMS,
|
||||
"The 'data' parameter must be a JSON object, not a JSON string. Please provide valid JSON without comments.".to_string(),
|
||||
None,
|
||||
));
|
||||
}
|
||||
|
||||
if allow_array {
|
||||
if !data_value.is_object() && !data_value.is_array() {
|
||||
return Err(ErrorData::new(
|
||||
ErrorCode::INVALID_PARAMS,
|
||||
"The 'data' parameter must be a JSON object or array.".to_string(),
|
||||
None,
|
||||
));
|
||||
}
|
||||
} else if !data_value.is_object() {
|
||||
return Err(ErrorData::new(
|
||||
ErrorCode::INVALID_PARAMS,
|
||||
"The 'data' parameter must be a JSON object.".to_string(),
|
||||
None,
|
||||
));
|
||||
}
|
||||
|
||||
Ok(data_value.clone())
|
||||
}
|
||||
|
||||
fn validation_err(msg: impl Into<String>) -> ErrorData {
|
||||
ErrorData::new(ErrorCode::INVALID_PARAMS, msg.into(), None)
|
||||
}
|
||||
@@ -890,16 +853,8 @@ Example:
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
let inner = params.0;
|
||||
inner.data.validate()?;
|
||||
let data = validate_data_param(
|
||||
&serde_json::to_value(inner).map_err(|e| {
|
||||
ErrorData::new(
|
||||
ErrorCode::INVALID_PARAMS,
|
||||
format!("Invalid parameters: {}", e),
|
||||
None,
|
||||
)
|
||||
})?,
|
||||
false,
|
||||
)?;
|
||||
let data = serde_json::to_value(inner.data)
|
||||
.map_err(|e| validation_err(format!("Invalid parameters: {e}")))?;
|
||||
|
||||
let node_count = data
|
||||
.get("nodes")
|
||||
@@ -954,16 +909,8 @@ Example:
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
let inner = params.0;
|
||||
inner.data.validate()?;
|
||||
let data = validate_data_param(
|
||||
&serde_json::to_value(inner).map_err(|e| {
|
||||
ErrorData::new(
|
||||
ErrorCode::INVALID_PARAMS,
|
||||
format!("Invalid parameters: {}", e),
|
||||
None,
|
||||
)
|
||||
})?,
|
||||
false,
|
||||
)?;
|
||||
let data = serde_json::to_value(inner.data)
|
||||
.map_err(|e| validation_err(format!("Invalid parameters: {e}")))?;
|
||||
|
||||
let label_count = data
|
||||
.get("labels")
|
||||
@@ -1033,16 +980,8 @@ Example multiple charts (array of chart objects):
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
let inner = params.0;
|
||||
validate_donut_charts(&inner.data)?;
|
||||
let data = validate_data_param(
|
||||
&serde_json::to_value(inner).map_err(|e| {
|
||||
ErrorData::new(
|
||||
ErrorCode::INVALID_PARAMS,
|
||||
format!("Invalid parameters: {}", e),
|
||||
None,
|
||||
)
|
||||
})?,
|
||||
true,
|
||||
)?;
|
||||
let data = serde_json::to_value(inner.data)
|
||||
.map_err(|e| validation_err(format!("Invalid parameters: {e}")))?;
|
||||
|
||||
let charts = data.as_array().ok_or_else(|| {
|
||||
ErrorData::new(
|
||||
@@ -1101,16 +1040,8 @@ Example:
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
let inner = params.0;
|
||||
inner.data.validate()?;
|
||||
let data = validate_data_param(
|
||||
&serde_json::to_value(inner).map_err(|e| {
|
||||
ErrorData::new(
|
||||
ErrorCode::INVALID_PARAMS,
|
||||
format!("Invalid parameters: {}", e),
|
||||
None,
|
||||
)
|
||||
})?,
|
||||
false,
|
||||
)?;
|
||||
let data = serde_json::to_value(inner.data)
|
||||
.map_err(|e| validation_err(format!("Invalid parameters: {e}")))?;
|
||||
|
||||
let root_name = data.get("name").and_then(|v| v.as_str()).unwrap_or("Root");
|
||||
let child_count = data
|
||||
@@ -1157,16 +1088,8 @@ Example:
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
let inner = params.0;
|
||||
inner.data.validate()?;
|
||||
let data = validate_data_param(
|
||||
&serde_json::to_value(inner).map_err(|e| {
|
||||
ErrorData::new(
|
||||
ErrorCode::INVALID_PARAMS,
|
||||
format!("Invalid parameters: {}", e),
|
||||
None,
|
||||
)
|
||||
})?,
|
||||
false,
|
||||
)?;
|
||||
let data = serde_json::to_value(inner.data)
|
||||
.map_err(|e| validation_err(format!("Invalid parameters: {e}")))?;
|
||||
|
||||
let entity_count = data
|
||||
.get("labels")
|
||||
@@ -1223,16 +1146,8 @@ Example:
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
let inner = params.0;
|
||||
inner.data.validate()?;
|
||||
let data = validate_data_param(
|
||||
&serde_json::to_value(inner).map_err(|e| {
|
||||
ErrorData::new(
|
||||
ErrorCode::INVALID_PARAMS,
|
||||
format!("Invalid parameters: {}", e),
|
||||
None,
|
||||
)
|
||||
})?,
|
||||
false,
|
||||
)?;
|
||||
let data = serde_json::to_value(inner.data)
|
||||
.map_err(|e| validation_err(format!("Invalid parameters: {e}")))?;
|
||||
|
||||
let title = data
|
||||
.get("title")
|
||||
@@ -1317,16 +1232,8 @@ Example:
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
let inner = params.0;
|
||||
inner.data.validate()?;
|
||||
let data = validate_data_param(
|
||||
&serde_json::to_value(inner).map_err(|e| {
|
||||
ErrorData::new(
|
||||
ErrorCode::INVALID_PARAMS,
|
||||
format!("Invalid parameters: {}", e),
|
||||
None,
|
||||
)
|
||||
})?,
|
||||
false,
|
||||
)?;
|
||||
let data = serde_json::to_value(inner.data)
|
||||
.map_err(|e| validation_err(format!("Invalid parameters: {e}")))?;
|
||||
|
||||
// Build a text fallback describing the chart for non-UI hosts
|
||||
let chart_type = data.get("type").and_then(|v| v.as_str()).unwrap_or("chart");
|
||||
@@ -1360,141 +1267,6 @@ mod tests {
|
||||
use super::*;
|
||||
use rmcp::handler::server::wrapper::Parameters;
|
||||
use rmcp::model::ContentBlock;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn test_validate_data_param_rejects_string() {
|
||||
// Test that a string value for data is rejected
|
||||
let params = json!({
|
||||
"data": "{\"labels\": [\"A\", \"B\"], \"matrix\": [[0, 1], [1, 0]]}"
|
||||
});
|
||||
|
||||
let result = validate_data_param(¶ms, false);
|
||||
assert!(result.is_err());
|
||||
|
||||
let err = result.unwrap_err();
|
||||
assert_eq!(err.code, ErrorCode::INVALID_PARAMS);
|
||||
assert!(err
|
||||
.message
|
||||
.contains("must be a JSON object, not a JSON string"));
|
||||
assert!(err.message.contains("without comments"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_data_param_accepts_object() {
|
||||
// Test that a proper object is accepted
|
||||
let params = json!({
|
||||
"data": {
|
||||
"labels": ["A", "B"],
|
||||
"matrix": [[0, 1], [1, 0]]
|
||||
}
|
||||
});
|
||||
|
||||
let result = validate_data_param(¶ms, false);
|
||||
assert!(result.is_ok());
|
||||
|
||||
let data = result.unwrap();
|
||||
assert!(data.is_object());
|
||||
assert_eq!(data["labels"][0], "A");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_data_param_rejects_array_when_not_allowed() {
|
||||
// Test that an array is rejected when allow_array is false
|
||||
let params = json!({
|
||||
"data": [
|
||||
{"label": "A", "value": 10},
|
||||
{"label": "B", "value": 20}
|
||||
]
|
||||
});
|
||||
|
||||
let result = validate_data_param(¶ms, false);
|
||||
assert!(result.is_err());
|
||||
|
||||
let err = result.unwrap_err();
|
||||
assert_eq!(err.code, ErrorCode::INVALID_PARAMS);
|
||||
assert!(err.message.contains("must be a JSON object"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_data_param_accepts_array_when_allowed() {
|
||||
// Test that an array is accepted when allow_array is true
|
||||
let params = json!({
|
||||
"data": [
|
||||
{"label": "A", "value": 10},
|
||||
{"label": "B", "value": 20}
|
||||
]
|
||||
});
|
||||
|
||||
let result = validate_data_param(¶ms, true);
|
||||
assert!(result.is_ok());
|
||||
|
||||
let data = result.unwrap();
|
||||
assert!(data.is_array());
|
||||
assert_eq!(data[0]["label"], "A");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_data_param_missing_data() {
|
||||
// Test that missing data parameter is rejected
|
||||
let params = json!({
|
||||
"other": "value"
|
||||
});
|
||||
|
||||
let result = validate_data_param(¶ms, false);
|
||||
assert!(result.is_err());
|
||||
|
||||
let err = result.unwrap_err();
|
||||
assert_eq!(err.code, ErrorCode::INVALID_PARAMS);
|
||||
assert!(err.message.contains("Missing 'data' parameter"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_data_param_rejects_primitive_values() {
|
||||
// Test that primitive values (number, boolean) are rejected
|
||||
let params_number = json!({
|
||||
"data": 42
|
||||
});
|
||||
|
||||
let result = validate_data_param(¶ms_number, false);
|
||||
assert!(result.is_err());
|
||||
|
||||
let params_bool = json!({
|
||||
"data": true
|
||||
});
|
||||
|
||||
let result = validate_data_param(¶ms_bool, false);
|
||||
assert!(result.is_err());
|
||||
|
||||
let params_null = json!({
|
||||
"data": null
|
||||
});
|
||||
|
||||
let result = validate_data_param(¶ms_null, false);
|
||||
assert!(result.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_data_param_with_json_containing_comments_as_string() {
|
||||
// Test that JSON with comments passed as a string is rejected
|
||||
let params = json!({
|
||||
"data": r#"{
|
||||
"labels": ["A", "B"],
|
||||
"matrix": [
|
||||
[0, 1], // This is a comment
|
||||
[1, 0] /* Another comment */
|
||||
]
|
||||
}"#
|
||||
});
|
||||
|
||||
let result = validate_data_param(¶ms, false);
|
||||
assert!(result.is_err());
|
||||
|
||||
let err = result.unwrap_err();
|
||||
assert_eq!(err.code, ErrorCode::INVALID_PARAMS);
|
||||
assert!(err.message.contains("not a JSON string"));
|
||||
assert!(err.message.contains("without comments"));
|
||||
}
|
||||
|
||||
fn assert_mcp_apps_result(
|
||||
tool_result: &CallToolResult,
|
||||
@@ -1787,9 +1559,7 @@ mod donut_format_tests {
|
||||
|
||||
fn round_trip(input: serde_json::Value) -> Result<serde_json::Value, String> {
|
||||
let parsed: RenderDonutParams = serde_json::from_value(input).map_err(|e| e.to_string())?;
|
||||
let serialized = serde_json::to_value(&parsed).map_err(|e| e.to_string())?;
|
||||
// Simulate validate_data_param extracting "data"
|
||||
Ok(serialized.get("data").cloned().unwrap_or(serialized))
|
||||
serde_json::to_value(&parsed.data).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -404,7 +404,6 @@ mod tests {
|
||||
use crate::agents::{AgentConfig, GoosePlatform};
|
||||
use crate::config::permission::PermissionManager;
|
||||
use crate::config::GooseMode;
|
||||
use crate::execution::SessionExecutionMode;
|
||||
use crate::session::SessionManager;
|
||||
|
||||
use super::AgentManager;
|
||||
@@ -422,26 +421,6 @@ mod tests {
|
||||
AgentManager::new(agent_config, Some(100)).await.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_execution_mode_constructors() {
|
||||
assert_eq!(
|
||||
SessionExecutionMode::chat(),
|
||||
SessionExecutionMode::Interactive
|
||||
);
|
||||
assert_eq!(
|
||||
SessionExecutionMode::scheduled(),
|
||||
SessionExecutionMode::Background
|
||||
);
|
||||
|
||||
let parent = "parent-123".to_string();
|
||||
assert_eq!(
|
||||
SessionExecutionMode::task(parent.clone()),
|
||||
SessionExecutionMode::SubTask {
|
||||
parent_session: parent
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_session_isolation() {
|
||||
let temp_dir = TempDir::new().unwrap();
|
||||
|
||||
@@ -8,42 +8,3 @@ pub mod manager;
|
||||
|
||||
pub use active_run::ActiveRunRegistry;
|
||||
pub(crate) use active_run::StartRunError;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fmt;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum SessionExecutionMode {
|
||||
Interactive,
|
||||
Background,
|
||||
SubTask { parent_session: String },
|
||||
}
|
||||
|
||||
impl SessionExecutionMode {
|
||||
/// Create an interactive chat mode
|
||||
pub fn chat() -> Self {
|
||||
Self::Interactive
|
||||
}
|
||||
|
||||
/// Create a background/scheduled mode
|
||||
pub fn scheduled() -> Self {
|
||||
Self::Background
|
||||
}
|
||||
|
||||
/// Create a sub-task mode with parent reference
|
||||
pub fn task(parent: String) -> Self {
|
||||
Self::SubTask {
|
||||
parent_session: parent,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for SessionExecutionMode {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Interactive => write!(f, "interactive"),
|
||||
Self::Background => write!(f, "background"),
|
||||
Self::SubTask { parent_session } => write!(f, "subtask(parent: {})", parent_session),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,9 +36,6 @@ pub const CODEX_KNOWN_MODELS: &[&str] = &[
|
||||
];
|
||||
pub const CODEX_DOC_URL: &str = "https://developers.openai.com/codex/cli";
|
||||
|
||||
/// Valid reasoning effort levels for Codex
|
||||
pub const CODEX_REASONING_LEVELS: &[&str] = &["none", "low", "medium", "high", "xhigh"];
|
||||
|
||||
/// Spawns the Codex CLI (`codex exec`) as a one-shot child process per turn.
|
||||
/// Text prompt is piped via stdin (`-`), images are passed as temporary files
|
||||
/// via the `-i` flag. Output is JSONL on stdout (`--json`), with events like
|
||||
@@ -85,15 +82,6 @@ impl CodexProvider {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn supports_reasoning_effort(_model_name: &str, reasoning_effort: &str) -> bool {
|
||||
if !CODEX_REASONING_LEVELS.contains(&reasoning_effort) {
|
||||
return false;
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
/// Apply permission flags based on GooseMode
|
||||
fn apply_permission_flags(
|
||||
cmd: &mut Command,
|
||||
@@ -1050,30 +1038,6 @@ printf '%s\n' '{"type":"item.completed","item":{"type":"agent_message","text":"p
|
||||
assert!(result.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_reasoning_level_validation() {
|
||||
assert!(CODEX_REASONING_LEVELS.contains(&"none"));
|
||||
assert!(CODEX_REASONING_LEVELS.contains(&"low"));
|
||||
assert!(CODEX_REASONING_LEVELS.contains(&"medium"));
|
||||
assert!(CODEX_REASONING_LEVELS.contains(&"high"));
|
||||
assert!(CODEX_REASONING_LEVELS.contains(&"xhigh"));
|
||||
assert!(!CODEX_REASONING_LEVELS.contains(&"minimal"));
|
||||
assert!(!CODEX_REASONING_LEVELS.contains(&"invalid"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_reasoning_effort_support_by_model() {
|
||||
assert!(CodexProvider::supports_reasoning_effort("gpt-5.2", "none"));
|
||||
assert!(CodexProvider::supports_reasoning_effort(
|
||||
"gpt-5.2-codex",
|
||||
"none"
|
||||
));
|
||||
assert!(CodexProvider::supports_reasoning_effort(
|
||||
"gpt-5.2-codex",
|
||||
"xhigh"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_known_models() {
|
||||
assert!(CODEX_KNOWN_MODELS.contains(&"gpt-5.2-codex"));
|
||||
|
||||
@@ -34,15 +34,6 @@ pub fn filter_extensions_from_system_prompt(system: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_google_model(payload: &Value) -> bool {
|
||||
payload
|
||||
.get("model")
|
||||
.and_then(|m| m.as_str())
|
||||
.unwrap_or("")
|
||||
.to_lowercase()
|
||||
.contains("google")
|
||||
}
|
||||
|
||||
/// Extract the model name from a JSON object. Common with most providers to have this top level attribute.
|
||||
pub fn get_model(data: &Value) -> String {
|
||||
if let Some(model) = data.get("model") {
|
||||
@@ -56,39 +47,6 @@ pub fn get_model(data: &Value) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn unescape_json_values(value: &Value) -> Value {
|
||||
let mut cloned = value.clone();
|
||||
unescape_json_values_in_place(&mut cloned);
|
||||
cloned
|
||||
}
|
||||
|
||||
fn unescape_json_values_in_place(value: &mut Value) {
|
||||
match value {
|
||||
Value::Object(map) => {
|
||||
for v in map.values_mut() {
|
||||
unescape_json_values_in_place(v);
|
||||
}
|
||||
}
|
||||
Value::Array(arr) => {
|
||||
for v in arr.iter_mut() {
|
||||
unescape_json_values_in_place(v);
|
||||
}
|
||||
}
|
||||
Value::String(s) if s.contains('\\') => {
|
||||
*s = s
|
||||
.replace("\\\\n", "\n")
|
||||
.replace("\\\\t", "\t")
|
||||
.replace("\\\\r", "\r")
|
||||
.replace("\\\\\"", "\"")
|
||||
.replace("\\n", "\n")
|
||||
.replace("\\t", "\t")
|
||||
.replace("\\r", "\r")
|
||||
.replace("\\\"", "\"");
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub const LOGS_TO_KEEP: usize = 10;
|
||||
|
||||
static INIT_LOGGER: OnceLock<Result<()>> = OnceLock::new();
|
||||
@@ -185,78 +143,3 @@ impl Drop for FileLogHandle {
|
||||
let _ = self.finish();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn unescape_json_values_with_object() {
|
||||
let value = json!({"text": "Hello\\nWorld"});
|
||||
let unescaped_value = unescape_json_values(&value);
|
||||
assert_eq!(unescaped_value, json!({"text": "Hello\nWorld"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unescape_json_values_with_array() {
|
||||
let value = json!(["Hello\\nWorld", "Goodbye\\tWorld"]);
|
||||
let unescaped_value = unescape_json_values(&value);
|
||||
assert_eq!(unescaped_value, json!(["Hello\nWorld", "Goodbye\tWorld"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unescape_json_values_with_string() {
|
||||
let value = json!("Hello\\nWorld");
|
||||
let unescaped_value = unescape_json_values(&value);
|
||||
assert_eq!(unescaped_value, json!("Hello\nWorld"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unescape_json_values_with_mixed_content() {
|
||||
let value = json!({
|
||||
"text": "Hello\\nWorld\\\\n!",
|
||||
"array": ["Goodbye\\tWorld", "See you\\rlater"],
|
||||
"nested": {
|
||||
"inner_text": "Inner\\\"Quote\\\""
|
||||
}
|
||||
});
|
||||
let unescaped_value = unescape_json_values(&value);
|
||||
assert_eq!(
|
||||
unescaped_value,
|
||||
json!({
|
||||
"text": "Hello\nWorld\n!",
|
||||
"array": ["Goodbye\tWorld", "See you\rlater"],
|
||||
"nested": {
|
||||
"inner_text": "Inner\"Quote\""
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unescape_json_values_with_no_escapes() {
|
||||
let value = json!({"text": "Hello World"});
|
||||
let unescaped_value = unescape_json_values(&value);
|
||||
assert_eq!(unescaped_value, json!({"text": "Hello World"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_google_model() {
|
||||
// Define the test cases as a vector of tuples
|
||||
let test_cases = vec![
|
||||
// (input, expected_result)
|
||||
(json!({ "model": "google_gemini" }), true),
|
||||
(json!({ "model": "microsoft_bing" }), false),
|
||||
(json!({ "model": "" }), false),
|
||||
(json!({}), false),
|
||||
(json!({ "model": "Google_XYZ" }), true),
|
||||
(json!({ "model": "google_abc" }), true),
|
||||
];
|
||||
|
||||
// Iterate through each test case and assert the result
|
||||
for (payload, expected_result) in test_cases {
|
||||
assert_eq!(is_google_model(&payload), expected_result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
pub mod langfuse_layer;
|
||||
mod observation_layer;
|
||||
pub mod rate_limiter;
|
||||
|
||||
pub use langfuse_layer::{create_langfuse_observer, LangfuseBatchManager};
|
||||
pub use observation_layer::{
|
||||
flatten_metadata, map_level, BatchManager, ObservationLayer, SpanData, SpanTracker,
|
||||
};
|
||||
pub use rate_limiter::{
|
||||
MetricData, RateLimitedTelemetrySender, SpanData as RateLimitedSpanData, TelemetryEvent,
|
||||
};
|
||||
|
||||
@@ -1,143 +0,0 @@
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::time::sleep;
|
||||
use tracing::{info, warn};
|
||||
|
||||
pub struct RateLimitedTelemetrySender {
|
||||
sender: mpsc::UnboundedSender<TelemetryEvent>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum TelemetryEvent {
|
||||
Span(SpanData),
|
||||
Metric(MetricData),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SpanData {
|
||||
pub name: String,
|
||||
pub attributes: Vec<(String, String)>,
|
||||
pub duration: Option<Duration>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct MetricData {
|
||||
pub name: String,
|
||||
pub value: f64,
|
||||
pub labels: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
impl RateLimitedTelemetrySender {
|
||||
pub fn new(rate_limit_ms: u64) -> Self {
|
||||
let (sender, mut receiver) = mpsc::unbounded_channel::<TelemetryEvent>();
|
||||
|
||||
tokio::spawn(async move {
|
||||
let mut last_send = Instant::now();
|
||||
let rate_limit_duration = Duration::from_millis(rate_limit_ms);
|
||||
|
||||
info!(
|
||||
"Starting rate-limited telemetry sender with {}ms delay",
|
||||
rate_limit_ms
|
||||
);
|
||||
|
||||
while let Some(event) = receiver.recv().await {
|
||||
let elapsed = last_send.elapsed();
|
||||
if elapsed < rate_limit_duration {
|
||||
let sleep_duration = rate_limit_duration - elapsed;
|
||||
sleep(sleep_duration).await;
|
||||
}
|
||||
|
||||
match event {
|
||||
TelemetryEvent::Span(span_data) => {
|
||||
Self::process_span(span_data);
|
||||
}
|
||||
TelemetryEvent::Metric(metric_data) => {
|
||||
Self::process_metric(metric_data);
|
||||
}
|
||||
}
|
||||
|
||||
last_send = Instant::now();
|
||||
}
|
||||
|
||||
warn!("Rate-limited telemetry sender shutting down");
|
||||
});
|
||||
|
||||
Self { sender }
|
||||
}
|
||||
|
||||
pub fn send_span(
|
||||
&self,
|
||||
span_data: SpanData,
|
||||
) -> Result<(), mpsc::error::SendError<TelemetryEvent>> {
|
||||
self.sender.send(TelemetryEvent::Span(span_data))
|
||||
}
|
||||
|
||||
pub fn send_metric(
|
||||
&self,
|
||||
metric_data: MetricData,
|
||||
) -> Result<(), mpsc::error::SendError<TelemetryEvent>> {
|
||||
self.sender.send(TelemetryEvent::Metric(metric_data))
|
||||
}
|
||||
|
||||
fn process_span(span_data: SpanData) {
|
||||
let span = tracing::info_span!("telemetry_span", name = %span_data.name);
|
||||
let _enter = span.enter();
|
||||
|
||||
for (key, value) in span_data.attributes {
|
||||
tracing::Span::current().record(key.as_str(), value.as_str());
|
||||
}
|
||||
|
||||
if let Some(duration) = span_data.duration {
|
||||
info!(duration_ms = duration.as_millis(), "span_duration");
|
||||
}
|
||||
}
|
||||
|
||||
fn process_metric(metric_data: MetricData) {
|
||||
info!(
|
||||
metric_name = %metric_data.name,
|
||||
metric_value = metric_data.value,
|
||||
labels = ?metric_data.labels,
|
||||
"telemetry_metric"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for RateLimitedTelemetrySender {
|
||||
fn default() -> Self {
|
||||
Self::new(400)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tokio::time::{timeout, Duration as TokioDuration};
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_rate_limited_sender() {
|
||||
let sender = RateLimitedTelemetrySender::new(100); // 100ms rate limit for testing
|
||||
|
||||
let span_data = SpanData {
|
||||
name: "test_span".to_string(),
|
||||
attributes: vec![("key".to_string(), "value".to_string())],
|
||||
duration: Some(Duration::from_millis(50)),
|
||||
};
|
||||
|
||||
let metric_data = MetricData {
|
||||
name: "test_metric".to_string(),
|
||||
value: 42.0,
|
||||
labels: vec![("label".to_string(), "value".to_string())],
|
||||
};
|
||||
|
||||
// Send events
|
||||
assert!(sender.send_span(span_data).is_ok());
|
||||
assert!(sender.send_metric(metric_data).is_ok());
|
||||
|
||||
// Give time for processing
|
||||
timeout(TokioDuration::from_millis(500), async {
|
||||
tokio::time::sleep(TokioDuration::from_millis(300)).await;
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user