### Metainfo Usage Example Source: https://github.com/cloudwego/metainfo/blob/main/README.md Demonstrates how to create, insert, get, derive, and remove typed information using the Metainfo struct. It highlights mutable scope and data persistence through derived MetaInfo instances. This example requires the `metainfo` crate. ```rust use metainfo::MetaInfo; fn test() { let mut m1 = MetaInfo::new(); m1.insert::(2); assert_eq!(*m1.get::().unwrap(), 2); let (mut m1, mut m2) = m1.derive(); assert_eq!(*m2.get::().unwrap(), 2); m2.insert::(4); assert_eq!(*m2.get::().unwrap(), 4); m2.remove::(); assert_eq!(*m2.get::().unwrap(), 2); } ``` -------------------------------- ### Iterate Forward Metadata with Protocol Prefixes Source: https://context7.com/cloudwego/metainfo/llms.txt This example illustrates how to iterate through persistent and transient forward metadata with protocol prefixes using the `metainfo::MetaInfo` library. It shows how to collect metadata entries with both RPC and HTTP prefixes, useful for batch processing or inspection of metadata intended for different communication protocols. ```rust use metainfo::{MetaInfo, Forward}; fn iterate_forward_metadata() { let mut metainfo = MetaInfo::new(); // Add multiple metadata entries metainfo.set_persistent("trace_id", "trace-123"); metainfo.set_persistent("user_id", "user-456"); metainfo.set_transient("auth_token", "token-789"); // Iterate with RPC prefix for (key, value) in metainfo.iter_persistents_and_transients_with_rpc_prefix() { println!("{}: {}", key, value); // Output includes: // RPC_PERSIST_trace_id: trace-123 // RPC_PERSIST_user_id: user-456 } // Iterate with HTTP prefix let http_entries: Vec<_> = metainfo .iter_persistents_and_transients_with_http_prefix() .collect(); assert!(http_entries.len() >= 2); } ``` -------------------------------- ### Manage Backward Metadata: Set, Get, Delete Transient and Downstream Source: https://context7.com/cloudwego/metainfo/llms.txt This snippet demonstrates managing backward metadata using `metainfo::MetaInfo`. It covers setting backward transient metadata (for the immediate caller) and backward downstream metadata (from downstream services). It also shows how to retrieve and delete this backward metadata, essential for response information flow. ```rust use metainfo::{MetaInfo, Backward}; fn backward_metadata() { let mut metainfo = MetaInfo::new(); // Set backward transient metadata (response data for immediate caller) metainfo.set_backward_transient("server_version", "v1.2.3"); metainfo.set_backward_transient("processing_time_ms", "45"); // Set backward downstream metadata (from downstream services) metainfo.set_backward_downstream("database_latency", "12"); // Retrieve backward metadata assert_eq!( metainfo.get_backward_transient("server_version").unwrap().as_str(), "v1.2.3" ); assert_eq!( metainfo.get_backward_downstream("database_latency").unwrap().as_str(), "12" ); // Delete backward metadata metainfo.del_backward_transient("processing_time_ms"); assert!(metainfo.get_backward_transient("processing_time_ms").is_none()); } ``` -------------------------------- ### Manage Forward Metadata: Set, Get, Delete Persistent and Transient Source: https://context7.com/cloudwego/metainfo/llms.txt This snippet demonstrates how to manage forward metadata using `metainfo::MetaInfo`. It covers setting persistent metadata (propagates through the entire call chain), transient metadata (only for the next hop), and upstream metadata (received from a previous service). It also shows how to retrieve and delete this metadata. ```rust use metainfo::{MetaInfo, Forward}; fn forward_metadata() { let mut metainfo = MetaInfo::new(); // Set persistent metadata (propagates through entire call chain) metainfo.set_persistent("trace_id", "trace-12345"); metainfo.set_persistent("user_context", "admin"); // Set transient metadata (only for next hop) metainfo.set_transient("auth_token", "bearer-xyz"); // Set upstream metadata (received from previous service) metainfo.set_upstream("source_service", "api-gateway"); // Retrieve metadata assert_eq!(metainfo.get_persistent("trace_id").unwrap().as_str(), "trace-12345"); assert_eq!(metainfo.get_transient("auth_token").unwrap().as_str(), "bearer-xyz"); assert_eq!(metainfo.get_upstream("source_service").unwrap().as_str(), "api-gateway"); // Delete metadata metainfo.del_persistent("user_context"); assert!(metainfo.get_persistent("user_context").is_none()); } ``` -------------------------------- ### Convert Metadata Prefixes: RPC and HTTP Source: https://context7.com/cloudwego/metainfo/llms.txt This code demonstrates converting metadata to protocol-specific formats using RPC and HTTP prefixes with the `metainfo::MetaInfo` struct. It includes stripping prefixes when setting metadata and retrieving it with the appropriate prefixes for transmission. This is crucial for inter-service communication where different protocols are used. ```rust use metainfo::{MetaInfo, Forward}; fn protocol_prefix_conversion() { let mut metainfo = MetaInfo::new(); // Strip RPC prefix and set persistent metadata metainfo.strip_rpc_prefix_and_set_persistent("RPC_PERSIST_trace_id", "trace-123"); metainfo.strip_rpc_prefix_and_set_upstream("RPC_TRANSIT_request_id", "req-456"); // Retrieve without prefix assert_eq!(metainfo.get_persistent("trace_id").unwrap().as_str(), "trace-123"); assert_eq!(metainfo.get_upstream("request_id").unwrap().as_str(), "req-456"); // Get all with RPC prefix for transmission if let Some(map) = metainfo.get_all_persistents_and_transients_with_rpc_prefix() { assert_eq!(map.get("RPC_PERSIST_trace_id").unwrap().as_str(), "trace-123"); } // HTTP prefix handling metainfo.strip_http_prefix_and_set_persistent("rpc-persist-user-id", "12345"); assert_eq!(metainfo.get_persistent("user_id").unwrap().as_str(), "12345"); // Get all with HTTP prefix if let Some(map) = metainfo.get_all_persistents_and_transients_with_http_prefix() { assert_eq!(map.get("rpc-persist-user-id").unwrap().as_str(), "12345"); } } ``` -------------------------------- ### Backward Protocol Conversion with RPC and HTTP Prefixes Source: https://context7.com/cloudwego/metainfo/llms.txt Demonstrates converting backward metadata by stripping RPC and HTTP prefixes and setting downstream values. It also shows how to retrieve all backward transients with RPC prefixes and iterate with HTTP prefixes. This functionality is crucial for normalizing metadata across different communication protocols. ```rust use metainfo::{MetaInfo, Backward}; fn backward_protocol_conversion() { let mut metainfo = MetaInfo::new(); // Strip RPC prefix and set backward downstream metainfo.strip_rpc_prefix_and_set_backward_downstream( "RPC_BACKWARD_cache_hit", "true" ); assert_eq!( metainfo.get_backward_downstream("cache_hit").unwrap().as_str(), "true" ); // Strip HTTP prefix and set backward downstream metainfo.strip_http_prefix_and_set_backward_downstream( "rpc-backward-response-code", "200" ); assert_eq!( metainfo.get_backward_downstream("response_code").unwrap().as_str(), "200" ); // Get all backward transients with RPC prefix metainfo.set_backward_transient("status", "success"); if let Some(map) = metainfo.get_all_backward_transients_with_rpc_prefix() { // Contains entries with RPC_BACKWARD_ prefix assert!(map.len() > 0); } // Iterate with HTTP prefix for (key, value) in metainfo.iter_backward_transients_with_http_prefix() { println!("Backward: {}: {}", key, value); } } ``` -------------------------------- ### Rust: Basic MetaInfo Operations with Typed Values Source: https://context7.com/cloudwego/metainfo/llms.txt Demonstrates creating a MetaInfo instance, inserting and retrieving typed data (like i32 and String), checking for type existence, and removing values. It also shows how to clear all data from the instance. This is fundamental for managing contextual information. ```rust use metainfo::MetaInfo; fn basic_operations() { // Create a new MetaInfo instance let mut metainfo = MetaInfo::new(); // Insert typed values metainfo.insert::(42); metainfo.insert::("hello".to_string()); // Retrieve typed values assert_eq!(*metainfo.get::().unwrap(), 42); assert_eq!(metainfo.get::().unwrap(), "hello"); // Check if a type exists assert!(metainfo.contains::()); assert!(!metainfo.contains::()); // Remove a typed value let removed = metainfo.remove::(); assert_eq!(removed, Some(42)); assert!(metainfo.get::().is_none()); // Clear all data metainfo.clear(); assert!(metainfo.get::().is_none()); } ``` -------------------------------- ### Task-Local Storage Usage with MetaInfo Source: https://context7.com/cloudwego/metainfo/llms.txt Illustrates how to access MetaInfo through task-local storage in asynchronous contexts, utilizing the `task_local` feature. This allows for scoped metadata management within async tasks and spawned operations, ensuring consistent context propagation. It requires the `task_local` feature to be enabled. ```rust use metainfo::{MetaInfo, METAINFO}; #[cfg(feature = "task_local")] async fn task_local_usage() { let metainfo = MetaInfo::new(); // Run code with task-local MetaInfo METAINFO.scope(std::cell::RefCell::new(metainfo), async { // Access MetaInfo from task-local storage METAINFO.with(|mi| { let mut mi = mi.borrow_mut(); mi.insert::(42); mi.insert_string("request_id".into(), "req-123".into()); }); // Later in the same task METAINFO.with(|mi| { let mi = mi.borrow(); assert_eq!(*mi.get::().unwrap(), 42); assert_eq!(mi.get_string("request_id").unwrap().as_str(), "req-123"); }); // Spawn async operations that inherit the scope tokio::spawn(async { METAINFO.with(|mi| { let mi = mi.borrow(); // MetaInfo is available in spawned task println!("Request ID: {:?}", mi.get_string("request_id")); }); }).await.ok(); }).await; } ``` -------------------------------- ### Extending MetaInfo with Additional Metadata Source: https://context7.com/cloudwego/metainfo/llms.txt Shows how to merge metadata from multiple `MetaInfo` instances. The `extend` method allows combining data, with values from the additional `MetaInfo` overriding existing ones in the base instance. This is useful for layering configuration or data from different sources. ```rust use metainfo::MetaInfo; fn extend_metainfo() { let mut base = MetaInfo::new(); base.insert::(10); base.insert_string("service".into(), "api".into()); let mut additional = MetaInfo::new(); additional.insert::(20); // Will override additional.insert::("extended".to_string()); additional.insert_string("version".into(), "v1".into()); // Extend base with additional base.extend(additional); // Values are merged, with additional taking precedence assert_eq!(*base.get::().unwrap(), 20); assert_eq!(base.get::().unwrap(), "extended"); assert_eq!(base.get_string("service").unwrap().as_str(), "api"); assert_eq!(base.get_string("version").unwrap().as_str(), "v1"); } ``` -------------------------------- ### Rust: String Key-Value Operations with FastStr in MetaInfo Source: https://context7.com/cloudwego/metainfo/llms.txt Shows how to use `MetaInfo` for storing and retrieving string key-value pairs efficiently using `FastStr`. This method is suitable for metadata that doesn't require type safety beyond string representation. It includes insertion, retrieval, existence checks, and removal. ```rust use metainfo::MetaInfo; use faststr::FastStr; fn string_kv_operations() { let mut metainfo = MetaInfo::new(); // Insert string key-value pairs metainfo.insert_string(FastStr::new("user_id"), FastStr::new("12345")); metainfo.insert_string(FastStr::new("session"), FastStr::new("abc-xyz")); // Retrieve string values let user_id = metainfo.get_string("user_id"); assert_eq!(user_id.unwrap().as_str(), "12345"); // Check existence assert!(metainfo.contains_string("session")); assert!(!metainfo.contains_string("token")); // Remove string values let removed = metainfo.remove_string("session"); assert_eq!(removed.unwrap().as_str(), "abc-xyz"); assert!(!metainfo.contains_string("session")); } ``` -------------------------------- ### Rust: Typed FastStr Storage in MetaInfo Source: https://context7.com/cloudwego/metainfo/llms.txt Demonstrates storing and retrieving `FastStr` values with type safety using newtype wrappers. This approach allows distinguishing between different string-based metadata using distinct types, enhancing compile-time safety. Operations include insertion, retrieval, existence checks, and removal. ```rust use metainfo::MetaInfo; use faststr::FastStr; // Define newtype wrappers struct UserId; struct SessionToken; fn faststr_type_storage() { let mut metainfo = MetaInfo::new(); // Insert typed FastStr values metainfo.insert_faststr::(FastStr::new("user_123")); metainfo.insert_faststr::(FastStr::new("token_xyz")); // Retrieve typed FastStr values let user_id = metainfo.get_faststr::().unwrap(); assert_eq!(user_id.as_str(), "user_123"); // Check existence assert!(metainfo.contains_faststr::()); // Remove typed FastStr let removed = metainfo.remove_faststr::(); assert_eq!(removed.unwrap().as_str(), "user_123"); } ``` -------------------------------- ### Storing and Retrieving Complex Custom Types in MetaInfo Source: https://context7.com/cloudwego/metainfo/llms.txt Demonstrates the capability to store and retrieve custom, complex data structures (like structs) within `MetaInfo`. This allows for application-specific metadata management. It also shows how to derive a child scope that inherits the complex types from its parent. ```rust use metainfo::MetaInfo; #[derive(Debug, Clone)] struct RequestContext { user_id: u64, permissions: Vec, } #[derive(Debug, Clone)] struct TracingInfo { trace_id: String, span_id: String, } fn complex_types() { let mut metainfo = MetaInfo::new(); // Store complex custom types metainfo.insert(RequestContext { user_id: 12345, permissions: vec!["read".to_string(), "write".to_string()], }); metainfo.insert(TracingInfo { trace_id: "trace-abc-123".to_string(), span_id: "span-xyz-456".to_string(), }); // Retrieve and use complex types if let Some(ctx) = metainfo.get::() { assert_eq!(ctx.user_id, 12345); assert_eq!(ctx.permissions.len(), 2); } if let Some(tracing) = metainfo.get::() { println!("Trace: {}, Span: {}", tracing.trace_id, tracing.span_id); } // Create derived scope with inherited complex types let (parent, mut child) = metainfo.derive(); assert!(child.get::().is_some()); assert!(child.get::().is_some()); } ``` -------------------------------- ### Rust: Hierarchical Scoping and Inheritance in MetaInfo Source: https://context7.com/cloudwego/metainfo/llms.txt Illustrates how to create child scopes that inherit data from a parent MetaInfo instance using the `derive()` method. It shows that modifications in child scopes are isolated, and removing a value from a child allows access to the parent's value. ```rust use metainfo::MetaInfo; fn hierarchical_scope() { // Create parent scope with data let mut parent = MetaInfo::new(); parent.insert::(10); // Derive two child scopes let (mut child1, mut child2) = parent.derive(); // Children inherit parent's data assert_eq!(*child1.get::().unwrap(), 10); assert_eq!(*child2.get::().unwrap(), 10); // Child modifications don't affect each other child1.insert::(20); child2.insert::(30); assert_eq!(*child1.get::().unwrap(), 20); assert_eq!(*child2.get::().unwrap(), 30); // Removing from child reveals parent value child1.remove::(); assert_eq!(*child1.get::().unwrap(), 10); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.