diff --git a/Cargo.lock b/Cargo.lock index 1fb9c12252..9d32dd68af 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -825,7 +825,7 @@ checksum = "975982cdb7ad6a142be15bdf84aea7ec6a9e5d4d797c004d43185b24cfe4e684" dependencies = [ "clap", "heck 0.5.0", - "indexmap 2.6.0", + "indexmap 2.11.4", "log", "proc-macro2", "quote", @@ -1510,7 +1510,7 @@ dependencies = [ "http-body-util", "hyper", "hyper-multipart-rfc7578", - "indexmap 2.6.0", + "indexmap 2.11.4", "libdd-alloc", "libdd-profiling-protobuf", "lz4_flex", @@ -1725,6 +1725,7 @@ dependencies = [ "http-body-util", "httpmock", "hyper", + "indexmap 2.11.4", "libdd-tinybytes", "libdd-trace-normalization", "libdd-trace-protobuf", @@ -1775,7 +1776,7 @@ dependencies = [ "hyper", "hyper-rustls", "hyper-util", - "indexmap 2.6.0", + "indexmap 2.11.4", "libc", "maplit", "nix", @@ -2288,7 +2289,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "93563d740bc9ef04104f9ed6f86f1e3275c2cdafb95664e26584b9ca807a8ffe" dependencies = [ "fallible-iterator", - "indexmap 2.6.0", + "indexmap 2.11.4", "stable_deref_trait", ] @@ -2342,7 +2343,7 @@ dependencies = [ "futures-core", "futures-sink", "http", - "indexmap 2.6.0", + "indexmap 2.11.4", "slab", "tokio", "tokio-util", @@ -2835,13 +2836,14 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.6.0" +version = "2.11.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "707907fe3c25f5424cce2cb7e1cbcafee6bdbe735ca90ef77c29e84591e5b9da" +checksum = "4b0f83760fb341a774ed326568e19f5a863af4a952def8c39f9ab92fd95b88e5" dependencies = [ "equivalent", "hashbrown 0.15.1", "serde", + "serde_core", ] [[package]] @@ -3674,7 +3676,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4c5cc86750666a3ed20bdaf5ca2a0344f9c67674cae0515bec2da16fbaa47db" dependencies = [ "fixedbitset", - "indexmap 2.6.0", + "indexmap 2.11.4", ] [[package]] @@ -3849,7 +3851,7 @@ checksum = "714c75db297bc88a63783ffc6ab9f830698a6705aa0201416931759ef4c8183d" dependencies = [ "autocfg", "equivalent", - "indexmap 2.6.0", + "indexmap 2.11.4", ] [[package]] @@ -4633,7 +4635,7 @@ dependencies = [ "chrono", "hex", "indexmap 1.9.3", - "indexmap 2.6.0", + "indexmap 2.11.4", "serde", "serde_derive", "serde_json", @@ -4659,7 +4661,7 @@ version = "0.9.34+deprecated" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47" dependencies = [ - "indexmap 2.6.0", + "indexmap 2.11.4", "itoa", "ryu", "serde", @@ -5386,7 +5388,7 @@ version = "0.20.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "70f427fce4d84c72b5b732388bf4a9f4531b53f74e2887e3ecb2481f68f66d81" dependencies = [ - "indexmap 2.6.0", + "indexmap 2.11.4", "toml_datetime", "winnow 0.5.40", ] @@ -5397,7 +5399,7 @@ version = "0.22.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "310068873db2c5b3e7659d2cc35d21855dbafa50d1ce336397c666e3cb08137e" dependencies = [ - "indexmap 2.6.0", + "indexmap 2.11.4", "serde", "serde_spanned", "toml_datetime", @@ -6545,7 +6547,7 @@ dependencies = [ "flate2", "getrandom 0.3.2", "hmac", - "indexmap 2.6.0", + "indexmap 2.11.4", "liblzma", "memchr", "pbkdf2", diff --git a/LICENSE-3rdparty.yml b/LICENSE-3rdparty.yml index 4f7e1ef581..eabd54c238 100644 --- a/LICENSE-3rdparty.yml +++ b/LICENSE-3rdparty.yml @@ -14080,7 +14080,7 @@ third_party_libraries: IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - package_name: indexmap - package_version: 2.6.0 + package_version: 2.11.4 repository: https://github.com/indexmap-rs/indexmap license: Apache-2.0 OR MIT licenses: @@ -15881,6 +15881,13 @@ third_party_libraries: DEALINGS IN THE SOFTWARE. - license: Apache-2.0 text: " Apache License\n Version 2.0, January 2004\n http://www.apache.org/licenses/\n\nTERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n1. Definitions.\n\n \"License\" shall mean the terms and conditions for use, reproduction,\n and distribution as defined by Sections 1 through 9 of this document.\n\n \"Licensor\" shall mean the copyright owner or entity authorized by\n the copyright owner that is granting the License.\n\n \"Legal Entity\" shall mean the union of the acting entity and all\n other entities that control, are controlled by, or are under common\n control with that entity. For the purposes of this definition,\n \"control\" means (i) the power, direct or indirect, to cause the\n direction or management of such entity, whether by contract or\n otherwise, or (ii) ownership of fifty percent (50%) or more of the\n outstanding shares, or (iii) beneficial ownership of such entity.\n\n \"You\" (or \"Your\") shall mean an individual or Legal Entity\n exercising permissions granted by this License.\n\n \"Source\" form shall mean the preferred form for making modifications,\n including but not limited to software source code, documentation\n source, and configuration files.\n\n \"Object\" form shall mean any form resulting from mechanical\n transformation or translation of a Source form, including but\n not limited to compiled object code, generated documentation,\n and conversions to other media types.\n\n \"Work\" shall mean the work of authorship, whether in Source or\n Object form, made available under the License, as indicated by a\n copyright notice that is included in or attached to the work\n (an example is provided in the Appendix below).\n\n \"Derivative Works\" shall mean any work, whether in Source or Object\n form, that is based on (or derived from) the Work and for which the\n editorial revisions, annotations, elaborations, or other modifications\n represent, as a whole, an original work of authorship. For the purposes\n of this License, Derivative Works shall not include works that remain\n separable from, or merely link (or bind by name) to the interfaces of,\n the Work and Derivative Works thereof.\n\n \"Contribution\" shall mean any work of authorship, including\n the original version of the Work and any modifications or additions\n to that Work or Derivative Works thereof, that is intentionally\n submitted to Licensor for inclusion in the Work by the copyright owner\n or by an individual or Legal Entity authorized to submit on behalf of\n the copyright owner. For the purposes of this definition, \"submitted\"\n means any form of electronic, verbal, or written communication sent\n to the Licensor or its representatives, including but not limited to\n communication on electronic mailing lists, source code control systems,\n and issue tracking systems that are managed by, or on behalf of, the\n Licensor for the purpose of discussing and improving the Work, but\n excluding communication that is conspicuously marked or otherwise\n designated in writing by the copyright owner as \"Not a Contribution.\"\n\n \"Contributor\" shall mean Licensor and any individual or Legal Entity\n on behalf of whom a Contribution has been received by Licensor and\n subsequently incorporated within the Work.\n\n2. Grant of Copyright License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n copyright license to reproduce, prepare Derivative Works of,\n publicly display, publicly perform, sublicense, and distribute the\n Work and such Derivative Works in Source or Object form.\n\n3. Grant of Patent License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n (except as stated in this section) patent license to make, have made,\n use, offer to sell, sell, import, and otherwise transfer the Work,\n where such license applies only to those patent claims licensable\n by such Contributor that are necessarily infringed by their\n Contribution(s) alone or by combination of their Contribution(s)\n with the Work to which such Contribution(s) was submitted. If You\n institute patent litigation against any entity (including a\n cross-claim or counterclaim in a lawsuit) alleging that the Work\n or a Contribution incorporated within the Work constitutes direct\n or contributory patent infringement, then any patent licenses\n granted to You under this License for that Work shall terminate\n as of the date such litigation is filed.\n\n4. Redistribution. You may reproduce and distribute copies of the\n Work or Derivative Works thereof in any medium, with or without\n modifications, and in Source or Object form, provided that You\n meet the following conditions:\n\n (a) You must give any other recipients of the Work or\n Derivative Works a copy of this License; and\n\n (b) You must cause any modified files to carry prominent notices\n stating that You changed the files; and\n\n (c) You must retain, in the Source form of any Derivative Works\n that You distribute, all copyright, patent, trademark, and\n attribution notices from the Source form of the Work,\n excluding those notices that do not pertain to any part of\n the Derivative Works; and\n\n (d) If the Work includes a \"NOTICE\" text file as part of its\n distribution, then any Derivative Works that You distribute must\n include a readable copy of the attribution notices contained\n within such NOTICE file, excluding those notices that do not\n pertain to any part of the Derivative Works, in at least one\n of the following places: within a NOTICE text file distributed\n as part of the Derivative Works; within the Source form or\n documentation, if provided along with the Derivative Works; or,\n within a display generated by the Derivative Works, if and\n wherever such third-party notices normally appear. The contents\n of the NOTICE file are for informational purposes only and\n do not modify the License. You may add Your own attribution\n notices within Derivative Works that You distribute, alongside\n or as an addendum to the NOTICE text from the Work, provided\n that such additional attribution notices cannot be construed\n as modifying the License.\n\n You may add Your own copyright statement to Your modifications and\n may provide additional or different license terms and conditions\n for use, reproduction, or distribution of Your modifications, or\n for any such Derivative Works as a whole, provided Your use,\n reproduction, and distribution of the Work otherwise complies with\n the conditions stated in this License.\n\n5. Submission of Contributions. Unless You explicitly state otherwise,\n any Contribution intentionally submitted for inclusion in the Work\n by You to the Licensor shall be under the terms and conditions of\n this License, without any additional terms or conditions.\n Notwithstanding the above, nothing herein shall supersede or modify\n the terms of any separate license agreement you may have executed\n with Licensor regarding such Contributions.\n\n6. Trademarks. This License does not grant permission to use the trade\n names, trademarks, service marks, or product names of the Licensor,\n except as required for reasonable and customary use in describing the\n origin of the Work and reproducing the content of the NOTICE file.\n\n7. Disclaimer of Warranty. Unless required by applicable law or\n agreed to in writing, Licensor provides the Work (and each\n Contributor provides its Contributions) on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n implied, including, without limitation, any warranties or conditions\n of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n PARTICULAR PURPOSE. You are solely responsible for determining the\n appropriateness of using or redistributing the Work and assume any\n risks associated with Your exercise of permissions under this License.\n\n8. Limitation of Liability. In no event and under no legal theory,\n whether in tort (including negligence), contract, or otherwise,\n unless required by applicable law (such as deliberate and grossly\n negligent acts) or agreed to in writing, shall any Contributor be\n liable to You for damages, including any direct, indirect, special,\n incidental, or consequential damages of any character arising as a\n result of this License or out of the use or inability to use the\n Work (including but not limited to damages for loss of goodwill,\n work stoppage, computer failure or malfunction, or any and all\n other commercial damages or losses), even if such Contributor\n has been advised of the possibility of such damages.\n\n9. Accepting Warranty or Additional Liability. While redistributing\n the Work or Derivative Works thereof, You may choose to offer,\n and charge a fee for, acceptance of support, warranty, indemnity,\n or other liability obligations and/or rights consistent with this\n License. However, in accepting such obligations, You may act only\n on Your own behalf and on Your sole responsibility, not on behalf\n of any other Contributor, and only if You agree to indemnify,\n defend, and hold each Contributor harmless for any liability\n incurred by, or claims asserted against, such Contributor by reason\n of your accepting any such warranty or additional liability.\n\nEND OF TERMS AND CONDITIONS\n\nAPPENDIX: How to apply the Apache License to your work.\n\n To apply the Apache License to your work, attach the following\n boilerplate notice, with the fields enclosed by brackets \"[]\"\n replaced with your own identifying information. (Don't include\n the brackets!) The text should be enclosed in the appropriate\n comment syntax for the file format. We also recommend that a\n file or class name and description of purpose be included on the\n same \"printed page\" as the copyright notice for easier\n identification within third-party archives.\n\nCopyright [yyyy] [name of copyright owner]\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n\thttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n" +- package_name: lz4_flex + package_version: 0.9.5 + repository: https://github.com/pseitz/lz4_flex + license: MIT + licenses: + - license: MIT + text: NOT FOUND - package_name: manual_future package_version: 0.1.1 repository: https://github.com/dmarcuse/manual_future.git @@ -27686,9 +27693,9 @@ third_party_libraries: - package_name: stringmetrics package_version: 2.2.2 repository: https://github.com/pluots/stringmetrics - license: License specified in file ($CARGO_HOME/registry/src/index.crates.io-6f17d22bba15001f/stringmetrics-2.2.2/LICENSE) + license: License specified in file ($CARGO_HOME/registry/src/github.com-25cdd57fae9f0462/stringmetrics-2.2.2/LICENSE) licenses: - - license: License specified in file ($CARGO_HOME/registry/src/index.crates.io-6f17d22bba15001f/stringmetrics-2.2.2/LICENSE) + - license: License specified in file ($CARGO_HOME/registry/src/github.com-25cdd57fae9f0462/stringmetrics-2.2.2/LICENSE) text: | Copyright 2022 Trevor Gross diff --git a/data-pipeline/tests/test_trace_exporter.rs b/data-pipeline/tests/test_trace_exporter.rs index 4b60844601..f6601fd6f8 100644 --- a/data-pipeline/tests/test_trace_exporter.rs +++ b/data-pipeline/tests/test_trace_exporter.rs @@ -94,7 +94,7 @@ mod tracing_integration_tests { Some(vec![("_top_level".to_string(), 1.0)]), ); - let traces = (dict.dict(), vec![vec![span_1, span_2, root_span]]); + let traces = (dict, vec![vec![span_1, span_2, root_span]]); rmp_serde::to_vec(&traces).unwrap() } diff --git a/datadog-profiling/Cargo.toml b/datadog-profiling/Cargo.toml index 7ea5837749..8709838845 100644 --- a/datadog-profiling/Cargo.toml +++ b/datadog-profiling/Cargo.toml @@ -31,7 +31,8 @@ http = "1.0" hyper = { workspace = true} http-body-util = "0.1" hyper-multipart-rfc7578 = "0.9.0" -indexmap = "2.2" +indexmap = "2.11" +lz4_flex = { version = "0.9", default-features = false, features = ["std", "safe-encode", "frame"] } mime = "0.3.16" prost = "0.13.5" rustc-hash = { version = "1.1", default-features = false } diff --git a/datadog-sidecar-ffi/src/span.rs b/datadog-sidecar-ffi/src/span.rs index ca13db00e5..40bccdd749 100644 --- a/datadog-sidecar-ffi/src/span.rs +++ b/datadog-sidecar-ffi/src/span.rs @@ -252,12 +252,12 @@ pub extern "C" fn ddog_get_span_type(span: &mut SpanBytes) -> CharSlice<'static> #[no_mangle] pub extern "C" fn ddog_set_span_trace_id(span: &mut SpanBytes, value: u64) { - span.trace_id = value; + span.trace_id = value as u128; } #[no_mangle] pub extern "C" fn ddog_get_span_trace_id(span: &mut SpanBytes) -> u64 { - span.trace_id + span.trace_id as u64 } #[no_mangle] diff --git a/datadog-trace-stats/benches/span_concentrator_bench.rs b/datadog-trace-stats/benches/span_concentrator_bench.rs index 33c1dd7b1b..977a148424 100644 --- a/datadog-trace-stats/benches/span_concentrator_bench.rs +++ b/datadog-trace-stats/benches/span_concentrator_bench.rs @@ -24,7 +24,7 @@ fn get_span(now: SystemTime, trace_id: u64, span_id: u64) -> SpanBytes { meta.insert("bucket_s3".into(), "aws_bucket".into()); } SpanBytes { - trace_id, + trace_id: trace_id as u128, span_id, service: "test-service".into(), name: "test-name".into(), diff --git a/datadog-trace-utils/Cargo.toml b/datadog-trace-utils/Cargo.toml index 8e235373f6..639fccd923 100644 --- a/datadog-trace-utils/Cargo.toml +++ b/datadog-trace-utils/Cargo.toml @@ -48,6 +48,7 @@ cargo_metadata = { version = "0.18.1", optional = true } cargo-platform = { version = "=0.1.7", optional = true } httpmock = { version = "0.8.0-alpha.1", optional = true } urlencoding = { version = "2.1.3", optional = true } +indexmap = "2.11" [dev-dependencies] bolero = "0.13" diff --git a/datadog-trace-utils/src/msgpack_decoder/v04/mod.rs b/datadog-trace-utils/src/msgpack_decoder/v04/mod.rs index 27c2918676..9c3aaa9360 100644 --- a/datadog-trace-utils/src/msgpack_decoder/v04/mod.rs +++ b/datadog-trace-utils/src/msgpack_decoder/v04/mod.rs @@ -619,7 +619,7 @@ mod tests { BytesString::from_slice(metric_key.as_ref()).unwrap(), metric_value.parse::().unwrap_or_default(), )]), - trace_id, + trace_id: trace_id as u128, span_id, parent_id, start, diff --git a/datadog-trace-utils/src/msgpack_decoder/v04/span.rs b/datadog-trace-utils/src/msgpack_decoder/v04/span.rs index d7f4e1feb6..7b37a5aea3 100644 --- a/datadog-trace-utils/src/msgpack_decoder/v04/span.rs +++ b/datadog-trace-utils/src/msgpack_decoder/v04/span.rs @@ -52,7 +52,7 @@ fn fill_span<'a>(span: &mut SpanSlice<'a>, buf: &mut &'a [u8]) -> Result<(), Dec SpanKey::Service => span.service = read_nullable_string(buf)?, SpanKey::Name => span.name = read_nullable_string(buf)?, SpanKey::Resource => span.resource = read_nullable_string(buf)?, - SpanKey::TraceId => span.trace_id = read_nullable_number_slice(buf)?, + SpanKey::TraceId => span.trace_id = read_nullable_number_slice::(buf)? as u128, SpanKey::SpanId => span.span_id = read_nullable_number_slice(buf)?, SpanKey::ParentId => span.parent_id = read_nullable_number_slice(buf)?, SpanKey::Start => span.start = read_nullable_number_slice(buf)?, diff --git a/datadog-trace-utils/src/msgpack_decoder/v05/mod.rs b/datadog-trace-utils/src/msgpack_decoder/v05/mod.rs index 7e2c486abf..f3960f7a88 100644 --- a/datadog-trace-utils/src/msgpack_decoder/v05/mod.rs +++ b/datadog-trace-utils/src/msgpack_decoder/v05/mod.rs @@ -197,7 +197,7 @@ fn deserialize_span<'a>(data: &mut &[u8], dict: &[&'a str]) -> Result(data)? as u128; span.span_id = read_number_slice(data)?; span.parent_id = read_number_slice(data)?; span.start = read_number_slice(data)?; diff --git a/datadog-trace-utils/src/msgpack_encoder/v04/span.rs b/datadog-trace-utils/src/msgpack_encoder/v04/span.rs index 0a0be27d2c..2d9207857c 100644 --- a/datadog-trace-utils/src/msgpack_encoder/v04/span.rs +++ b/datadog-trace-utils/src/msgpack_encoder/v04/span.rs @@ -207,7 +207,7 @@ pub fn encode_span( write_str(writer, span.resource.borrow())?; write_str(writer, "trace_id")?; - write_u64(writer, span.trace_id)?; + write_u64(writer, span.trace_id as u64)?; write_str(writer, "span_id")?; write_u64(writer, span.span_id)?; diff --git a/datadog-trace-utils/src/span/mod.rs b/datadog-trace-utils/src/span/mod.rs index a68f643ad1..4399ca42c9 100644 --- a/datadog-trace-utils/src/span/mod.rs +++ b/datadog-trace-utils/src/span/mod.rs @@ -63,7 +63,7 @@ impl FromStr for SpanKey { /// Trait representing the requirements for a type to be used as a Span "string" type. /// Note: Borrow is not required by the derived traits, but allows to access HashMap elements /// from a static str and check if the string is empty. -pub trait SpanText: Eq + Hash + Borrow + Serialize + Default + Clone { +pub trait SpanText: Eq + Hash + Borrow + Serialize + Default { fn from_static_str(value: &'static str) -> Self; } @@ -106,7 +106,8 @@ where pub resource: T, #[serde(skip_serializing_if = "is_empty_str")] pub r#type: T, - pub trace_id: u64, + #[serde(serialize_with = "serialize_lower_64_bits")] + pub trace_id: u128, pub span_id: u64, #[serde(skip_serializing_if = "is_default")] pub parent_id: u64, @@ -128,6 +129,13 @@ where pub span_events: Vec>, } +fn serialize_lower_64_bits(v: &u128, serializer: S) -> Result +where + S: serde::Serializer, +{ + serializer.serialize_u64(*v as u64) +} + /// The generic representation of a V04 span link. /// `T` is the type used to represent strings in the span link. #[derive(Clone, Debug, Default, PartialEq, Serialize)] diff --git a/datadog-trace-utils/src/span/trace_utils.rs b/datadog-trace-utils/src/span/trace_utils.rs index 04c2c69a6d..5583182aaa 100644 --- a/datadog-trace-utils/src/span/trace_utils.rs +++ b/datadog-trace-utils/src/span/trace_utils.rs @@ -34,26 +34,26 @@ pub fn compute_top_level_span(trace: &mut [Span]) where T: SpanText, { - let mut span_id_to_service: HashMap = HashMap::new(); - for span in trace.iter() { - span_id_to_service.insert(span.span_id, span.service.clone()); + let mut span_id_idx: HashMap = HashMap::new(); + for (i, span) in trace.iter().enumerate() { + span_id_idx.insert(span.span_id, i); } - for span in trace.iter_mut() { - let parent_id = span.parent_id; + for span_idx in 0..trace.len() { + let parent_id = trace[span_idx].parent_id; if parent_id == 0 { - set_top_level_span(span, true); + set_top_level_span(&mut trace[span_idx], true); continue; } - match span_id_to_service.get(&parent_id) { + match span_id_idx.get(&parent_id).map(|i| &trace[*i].service) { Some(parent_span_service) => { - if !parent_span_service.eq(&span.service) { + if !(parent_span_service == &trace[span_idx].service) { // parent is not in the same service - set_top_level_span(span, true) + set_top_level_span(&mut trace[span_idx], true) } } None => { // span has no parent in chunk - set_top_level_span(span, true) + set_top_level_span(&mut trace[span_idx], true) } } } @@ -173,7 +173,7 @@ mod tests { is_top_level: bool, ) -> SpanBytes { let mut span = SpanBytes { - trace_id, + trace_id: trace_id as u128, span_id, service: "test-service".into(), name: "test_name".into(), diff --git a/datadog-trace-utils/src/span/v05/dict.rs b/datadog-trace-utils/src/span/v05/dict.rs index 6ef7950e68..25a070922d 100644 --- a/datadog-trace-utils/src/span/v05/dict.rs +++ b/datadog-trace-utils/src/span/v05/dict.rs @@ -1,17 +1,23 @@ // Copyright 2021-Present Datadog, Inc. https://www.datadoghq.com/ // SPDX-License-Identifier: Apache-2.0 -use std::collections::HashMap; - use crate::span::SpanText; /// This struct represents the shared dictionary used for interning all the strings belonging to a /// v05 trace chunk. +#[derive(Debug, Clone)] pub struct SharedDict { - /// Map strings with their index (O(1) retrieval complexity). - string_map: HashMap, - /// Since the collection needs to be ordered an additional vector to keep the insertion order. - dict: Vec, + /// Map strings with their index and keep insertion order(O(1) retrieval complexity). + map: indexmap::IndexSet, +} + +impl serde::Serialize for SharedDict { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + serializer.collect_seq(self.map.iter().map(|entry| -> &str { entry.borrow() })) + } } impl SharedDict { @@ -21,28 +27,30 @@ impl SharedDict { /// # Arguments: /// /// * `str`: string to look up in the dictionary. - pub fn get_or_insert(&mut self, s: &T) -> Result { - if let Some(index) = self.string_map.get(s.borrow()) { - (*index).try_into() + pub fn get_or_insert(&mut self, s: T) -> Result { + if let Some(index) = self.map.get_index_of(s.borrow()) { + (index).try_into() } else { - let index = self.dict.len(); - self.dict.push(s.clone()); - self.string_map.insert(s.clone(), index); + let index = self.map.len(); + self.map.insert(s); index.try_into() } } - /// Returns the dictionary. This method consumes the structure. - pub fn dict(mut self) -> Vec { - std::mem::take(&mut self.dict) + #[allow(clippy::len_without_is_empty)] + pub fn len(&self) -> usize { + self.map.len() + } + + pub fn iter(&self) -> impl Iterator { + self.map.iter() } } impl Default for SharedDict { fn default() -> Self { Self { - string_map: HashMap::from([(T::default(), 0)]), - dict: vec![T::default()], + map: indexmap::indexset! {T::default()}, } } } @@ -57,31 +65,27 @@ mod tests { fn default_test() { let dict: SharedDict = SharedDict::default(); - assert_eq!(dict.string_map.len(), 1); - assert_eq!(dict.dict.len(), 1); + assert_eq!(dict.map.len(), 1); } #[test] fn get_or_insert_test() { let mut dict = SharedDict::default(); unsafe { - let _ = dict.get_or_insert(&BytesString::from_bytes_unchecked(Bytes::from_static( + let _ = dict.get_or_insert(BytesString::from_bytes_unchecked(Bytes::from_static( b"foo", ))); }; unsafe { - let _ = dict.get_or_insert(&BytesString::from_bytes_unchecked(Bytes::from_static( + let _ = dict.get_or_insert(BytesString::from_bytes_unchecked(Bytes::from_static( b"bar", ))); }; - assert_eq!(dict.string_map.len(), 3); - assert_eq!(dict.dict.len(), 3); + assert_eq!(dict.map.len(), 3); - let res = dict.dict(); - assert_eq!(res.len(), 3); - assert_eq!(res[0].as_str(), ""); - assert_eq!(res[1].as_str(), "foo"); - assert_eq!(res[2].as_str(), "bar"); + assert_eq!(dict.map[0].as_str(), ""); + assert_eq!(dict.map[1].as_str(), "foo"); + assert_eq!(dict.map[2].as_str(), "bar"); } } diff --git a/datadog-trace-utils/src/span/v05/mod.rs b/datadog-trace-utils/src/span/v05/mod.rs index abc3e5da1f..e21746e1c0 100644 --- a/datadog-trace-utils/src/span/v05/mod.rs +++ b/datadog-trace-utils/src/span/v05/mod.rs @@ -29,34 +29,36 @@ pub struct Span { } pub fn from_span( - span: &crate::span::Span, + span: crate::span::Span, dict: &mut SharedDict, ) -> Result { + let meta_len = span.meta.len(); + let metrics_len = span.metrics.len(); Ok(Span { - service: dict.get_or_insert(&span.service)?, - name: dict.get_or_insert(&span.name)?, - resource: dict.get_or_insert(&span.resource)?, - trace_id: span.trace_id, + service: dict.get_or_insert(span.service)?, + name: dict.get_or_insert(span.name)?, + resource: dict.get_or_insert(span.resource)?, + trace_id: span.trace_id as u64, span_id: span.span_id, parent_id: span.parent_id, start: span.start, duration: span.duration, error: span.error, - meta: span.meta.iter().try_fold( - HashMap::with_capacity(span.meta.len()), + meta: span.meta.into_iter().try_fold( + HashMap::with_capacity(meta_len), |mut meta, (k, v)| -> anyhow::Result> { meta.insert(dict.get_or_insert(k)?, dict.get_or_insert(v)?); Ok(meta) }, )?, - metrics: span.metrics.iter().try_fold( - HashMap::with_capacity(span.metrics.len()), + metrics: span.metrics.into_iter().try_fold( + HashMap::with_capacity(metrics_len), |mut metrics, (k, v)| -> anyhow::Result> { - metrics.insert(dict.get_or_insert(k)?, *v); + metrics.insert(dict.get_or_insert(k)?, v); Ok(metrics) }, )?, - r#type: dict.get_or_insert(&span.r#type)?, + r#type: dict.get_or_insert(span.r#type)?, }) } @@ -90,9 +92,7 @@ mod tests { }; let mut dict = SharedDict::default(); - let v05_span = from_span(&span, &mut dict).unwrap(); - - let dict = dict.dict(); + let v05_span = from_span(span, &mut dict).unwrap(); let get_index_from_str = |str: &str| -> u32 { dict.iter() diff --git a/datadog-trace-utils/src/test_utils/mod.rs b/datadog-trace-utils/src/test_utils/mod.rs index 7f57cf1d3a..3b8e61b904 100644 --- a/datadog-trace-utils/src/test_utils/mod.rs +++ b/datadog-trace-utils/src/test_utils/mod.rs @@ -34,7 +34,7 @@ pub fn create_test_no_alloc_span( is_top_level: bool, ) -> SpanBytes { let mut span = SpanBytes { - trace_id, + trace_id: trace_id as u128, span_id, service: BytesString::from_slice("test-service".as_ref()).unwrap(), name: BytesString::from_slice("test_name".as_ref()).unwrap(), @@ -234,18 +234,17 @@ pub fn create_test_v05_span( ) -> v05::Span { let mut meta = HashMap::from([ ( - dict.get_or_insert(&BytesString::from("service")).unwrap(), - dict.get_or_insert(&BytesString::from("test-service")) + dict.get_or_insert(BytesString::from("service")).unwrap(), + dict.get_or_insert(BytesString::from("test-service")) .unwrap(), ), ( - dict.get_or_insert(&BytesString::from("env")).unwrap(), - dict.get_or_insert(&BytesString::from("test-env")).unwrap(), + dict.get_or_insert(BytesString::from("env")).unwrap(), + dict.get_or_insert(BytesString::from("test-env")).unwrap(), ), ( - dict.get_or_insert(&BytesString::from("runtime-id")) - .unwrap(), - dict.get_or_insert(&BytesString::from("test-runtime-id-value")) + dict.get_or_insert(BytesString::from("runtime-id")).unwrap(), + dict.get_or_insert(BytesString::from("test-runtime-id-value")) .unwrap(), ), ]); @@ -253,31 +252,30 @@ pub fn create_test_v05_span( if is_top_level { meta.extend([ ( - dict.get_or_insert(&BytesString::from("functionname")) + dict.get_or_insert(BytesString::from("functionname")) .unwrap(), - dict.get_or_insert(&BytesString::from("dummy_function_name")) + dict.get_or_insert(BytesString::from("dummy_function_name")) .unwrap(), ), ( - dict.get_or_insert(&BytesString::from("_dd.origin")) - .unwrap(), - dict.get_or_insert(&BytesString::from("cloudfunction")) + dict.get_or_insert(BytesString::from("_dd.origin")).unwrap(), + dict.get_or_insert(BytesString::from("cloudfunction")) .unwrap(), ), ( - dict.get_or_insert(&BytesString::from("origin")).unwrap(), - dict.get_or_insert(&BytesString::from("cloudfunction")) + dict.get_or_insert(BytesString::from("origin")).unwrap(), + dict.get_or_insert(BytesString::from("cloudfunction")) .unwrap(), ), ]); } v05::Span { service: dict - .get_or_insert(&BytesString::from("test-service")) + .get_or_insert(BytesString::from("test-service")) .unwrap(), - name: dict.get_or_insert(&BytesString::from("test_name")).unwrap(), + name: dict.get_or_insert(BytesString::from("test_name")).unwrap(), resource: dict - .get_or_insert(&BytesString::from("test-resource")) + .get_or_insert(BytesString::from("test-resource")) .unwrap(), trace_id, span_id, @@ -289,15 +287,15 @@ pub fn create_test_v05_span( metrics: if let Some(metrics) = metrics { metrics .into_iter() - .map(|(k, v)| (dict.get_or_insert(&BytesString::from(k)).unwrap(), v)) + .map(|(k, v)| (dict.get_or_insert(BytesString::from(k)).unwrap(), v)) .collect() } else { HashMap::new() }, r#type: if is_top_level { - dict.get_or_insert(&BytesString::from("web")).unwrap() + dict.get_or_insert(BytesString::from("web")).unwrap() } else { - dict.get_or_insert(&BytesString::from("")).unwrap() + dict.get_or_insert(BytesString::from("")).unwrap() }, } } diff --git a/datadog-trace-utils/src/trace_utils.rs b/datadog-trace-utils/src/trace_utils.rs index a1a28be95c..4527f7eea2 100644 --- a/datadog-trace-utils/src/trace_utils.rs +++ b/datadog-trace-utils/src/trace_utils.rs @@ -606,8 +606,9 @@ pub fn collect_trace_chunks( let mut shared_dict = SharedDict::default(); let mut v05_traces: Vec> = Vec::with_capacity(traces.len()); for trace in traces { - let v05_trace = trace.iter().try_fold( - Vec::with_capacity(trace.len()), + let trace_len = trace.len(); + let v05_trace = trace.into_iter().try_fold( + Vec::with_capacity(trace_len), |mut acc, span| -> anyhow::Result> { acc.push(v05::from_span(span, &mut shared_dict)?); Ok(acc) @@ -616,7 +617,7 @@ pub fn collect_trace_chunks( v05_traces.push(v05_trace); } - Ok(TraceChunks::V05((shared_dict.dict(), v05_traces))) + Ok(TraceChunks::V05((shared_dict, v05_traces))) } else { Ok(TraceChunks::V04(traces)) } @@ -709,13 +710,15 @@ pub fn is_partial_snapshot(span: &pb::Span) -> bool { #[cfg(test)] mod tests { use super::*; - use crate::test_utils::{create_test_no_alloc_span, create_test_span}; + use crate::{ + span::SharedDictBytes, + test_utils::{create_test_no_alloc_span, create_test_span}, + }; use ddcommon::Endpoint; use hyper::Request; - use libdd_tinybytes::BytesString; use serde_json::json; - fn find_index_in_dict(dict: &[BytesString], value: &str) -> Option { + fn find_index_in_dict(dict: &SharedDictBytes, value: &str) -> Option { let idx = dict.iter().position(|e| e.as_str() == value); idx.map(|idx| idx.try_into().unwrap()) } diff --git a/datadog-trace-utils/src/tracer_payload.rs b/datadog-trace-utils/src/tracer_payload.rs index 0d5d2c955a..c0e118956e 100644 --- a/datadog-trace-utils/src/tracer_payload.rs +++ b/datadog-trace-utils/src/tracer_payload.rs @@ -1,7 +1,8 @@ // Copyright 2024-Present Datadog, Inc. https://www.datadoghq.com/ // SPDX-License-Identifier: Apache-2.0 -use crate::span::{v05, Span, SpanBytes, SpanText}; +use crate::span::v05::dict::SharedDict; +use crate::span::{v05, SharedDictBytes, Span, SpanBytes, SpanText}; use crate::trace_utils::collect_trace_chunks; use crate::{msgpack_decoder, trace_utils::cmp_send_data_payloads}; use libdd_tinybytes as tinybytes; @@ -27,7 +28,7 @@ pub enum TraceChunks { /// Collection of TraceChunkSpan. V04(Vec>>), /// Collection of TraceChunkSpan with de-duplicated strings. - V05((Vec, Vec>)), + V05((SharedDict, Vec>)), } impl TraceChunks { @@ -57,7 +58,7 @@ pub enum TracerPayloadCollection { /// Collection of TraceChunkSpan. V04(Vec>), /// Collection of TraceChunkSpan with de-duplicated strings. - V05((Vec, Vec>)), + V05((SharedDictBytes, Vec>)), } impl TracerPayloadCollection { diff --git a/ddcommon-ffi/src/option.rs b/ddcommon-ffi/src/option.rs index 2aaed3aed2..9c3eb9fb5f 100644 --- a/ddcommon-ffi/src/option.rs +++ b/ddcommon-ffi/src/option.rs @@ -1,6 +1,8 @@ // Copyright 2021-Present Datadog, Inc. https://www.datadoghq.com/ // SPDX-License-Identifier: Apache-2.0 +use std::fmt::Debug; + #[repr(C)] #[derive(Debug, PartialEq, Eq)] #[must_use] @@ -28,10 +30,14 @@ impl Option { } } - pub fn unwrap_none(self) { + #[track_caller] + pub fn unwrap_none(self) + where + T: Debug, + { match self { #[allow(clippy::panic)] - Option::Some(_) => panic!("Called ffi::Option::unwrap_none but option was Some(_)"), + Option::Some(s) => panic!("Called ffi::Option::unwrap_none but option was Some({s:?})"), Option::None => {} } } diff --git a/ddcommon/Cargo.toml b/ddcommon/Cargo.toml index fd5c45b8f0..1dab8a530b 100644 --- a/ddcommon/Cargo.toml +++ b/ddcommon/Cargo.toml @@ -58,7 +58,7 @@ hyper-rustls = { version = "0.27", default-features = false, features = [ ], optional = true } [dev-dependencies] -indexmap = "2.2" +indexmap = "2.11" maplit = "1.0" tempfile = "3.8"