From 22126443b80ae63078b000e4a40cfcd368866f0e Mon Sep 17 00:00:00 2001 From: AJ Stuyvenberg Date: Thu, 27 Jun 2024 11:05:19 -0400 Subject: [PATCH] Support v0.5 trace endpoint (#505) * feat: add Lambda * feat: env verifier * feat: set origin tag correctly * debug: what is v5 sending us * revert * feat: v0.5 trace decompression support * fix: remove comment and unwraps * feat: remove erroneous GCP comment from my copypasta * fix: complex type, license for rmpv * feat: Rename methods to use v05. Add v05 string method. Temp debugging log to figure out json string encoding stuff * wip: more debugging * fix: use into_str instead of to_string to avoid string escaping * feat: clean up match * feat: Rename last method to get_v05 nomenclature --- Cargo.lock | 16 +- LICENSE-3rdparty.yml | 30 ++- trace-mini-agent/src/env_verifier.rs | 3 + trace-utils/Cargo.toml | 4 +- trace-utils/src/config_utils.rs | 3 + trace-utils/src/trace_utils.rs | 294 +++++++++++++++++++++++++++ 6 files changed, 346 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f4f85e44f..1b0bca870 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1466,7 +1466,9 @@ dependencies = [ "log", "prost 0.11.9", "rand", + "rmp", "rmp-serde", + "rmpv", "serde", "serde_json", "tokio", @@ -3552,9 +3554,9 @@ dependencies = [ [[package]] name = "rmp" -version = "0.8.12" +version = "0.8.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f9860a6cc38ed1da53456442089b4dfa35e7cedaa326df63017af88385e6b20" +checksum = "228ed7c16fa39782c3b3468e974aec2795e9089153cd08ee2e9aefb3613334c4" dependencies = [ "byteorder", "num-traits", @@ -3572,6 +3574,16 @@ dependencies = [ "serde", ] +[[package]] +name = "rmpv" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58450723cd9ee93273ce44a20b6ec4efe17f8ed2e3631474387bfdecf18bb2a9" +dependencies = [ + "num-traits", + "rmp", +] + [[package]] name = "rustc-demangle" version = "0.1.23" diff --git a/LICENSE-3rdparty.yml b/LICENSE-3rdparty.yml index 7364e5bb2..1d836f45b 100644 --- a/LICENSE-3rdparty.yml +++ b/LICENSE-3rdparty.yml @@ -17062,7 +17062,7 @@ third_party_libraries: - license: License specified in file ($CARGO_HOME/registry/src/github.com-1ecc6299db9ec823/ring-0.17.8/LICENSE) text: "Note that it is easy for this file to get out of sync with the licenses in the\nsource code files. It's recommended to compare the licenses in the source code\nwith what's mentioned here.\n\n*ring* is derived from BoringSSL, so the licensing situation in *ring* is\nsimilar to BoringSSL.\n\n*ring* uses an ISC-style license like BoringSSL for code in new files,\nincluding in particular all the Rust code:\n\n Copyright 2015-2016 Brian Smith.\n\n Permission to use, copy, modify, and/or distribute this software for any\n purpose with or without fee is hereby granted, provided that the above\n copyright notice and this permission notice appear in all copies.\n\n THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHORS DISCLAIM ALL WARRANTIES\n WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY\n SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION\n OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN\n CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\nBoringSSL is a fork of OpenSSL. As such, large parts of it fall under OpenSSL\nlicensing. Files that are completely new have a Google copyright and an ISC\nlicense. This license is reproduced at the bottom of this file.\n\nContributors to BoringSSL are required to follow the CLA rules for Chromium:\nhttps://cla.developers.google.com/clas\n\nFiles in third_party/ have their own licenses, as described therein. The MIT\nlicense, for third_party/fiat, which, unlike other third_party directories, is\ncompiled into non-test libraries, is included below.\n\nThe OpenSSL toolkit stays under a dual license, i.e. both the conditions of the\nOpenSSL License and the original SSLeay license apply to the toolkit. See below\nfor the actual license texts. Actually both licenses are BSD-style Open Source\nlicenses. In case of any license issues related to OpenSSL please contact\nopenssl-core@openssl.org.\n\nThe following are Google-internal bug numbers where explicit permission from\nsome authors is recorded for use of their work:\n 27287199\n 27287880\n 27287883\n\n OpenSSL License\n ---------------\n\n/* ====================================================================\n * Copyright (c) 1998-2011 The OpenSSL Project. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and/or other materials provided with the\n * distribution.\n *\n * 3. All advertising materials mentioning features or use of this\n * software must display the following acknowledgment:\n * \"This product includes software developed by the OpenSSL Project\n * for use in the OpenSSL Toolkit. (http://www.openssl.org/)\"\n *\n * 4. The names \"OpenSSL Toolkit\" and \"OpenSSL Project\" must not be used to\n * endorse or promote products derived from this software without\n * prior written permission. For written permission, please contact\n * openssl-core@openssl.org.\n *\n * 5. Products derived from this software may not be called \"OpenSSL\"\n * nor may \"OpenSSL\" appear in their names without prior written\n * permission of the OpenSSL Project.\n *\n * 6. Redistributions of any form whatsoever must retain the following\n * acknowledgment:\n * \"This product includes software developed by the OpenSSL Project\n * for use in the OpenSSL Toolkit (http://www.openssl.org/)\"\n *\n * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY\n * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n * ====================================================================\n *\n * This product includes cryptographic software written by Eric Young\n * (eay@cryptsoft.com). This product includes software written by Tim\n * Hudson (tjh@cryptsoft.com).\n *\n */\n\n Original SSLeay License\n -----------------------\n\n/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)\n * All rights reserved.\n *\n * This package is an SSL implementation written\n * by Eric Young (eay@cryptsoft.com).\n * The implementation was written so as to conform with Netscapes SSL.\n * \n * This library is free for commercial and non-commercial use as long as\n * the following conditions are aheared to. The following conditions\n * apply to all code found in this distribution, be it the RC4, RSA,\n * lhash, DES, etc., code; not just the SSL code. The SSL documentation\n * included with this distribution is covered by the same copyright terms\n * except that the holder is Tim Hudson (tjh@cryptsoft.com).\n * \n * Copyright remains Eric Young's, and as such any Copyright notices in\n * the code are not to be removed.\n * If this package is used in a product, Eric Young should be given attribution\n * as the author of the parts of the library used.\n * This can be in the form of a textual message at program startup or\n * in documentation (online or textual) provided with the package.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. All advertising materials mentioning features or use of this software\n * must display the following acknowledgement:\n * \"This product includes cryptographic software written by\n * Eric Young (eay@cryptsoft.com)\"\n * The word 'cryptographic' can be left out if the rouines from the library\n * being used are not cryptographic related :-).\n * 4. If you include any Windows specific code (or a derivative thereof) from \n * the apps directory (application code) you must include an acknowledgement:\n * \"This product includes software written by Tim Hudson (tjh@cryptsoft.com)\"\n * \n * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * \n * The licence and distribution terms for any publically available version or\n * derivative of this code cannot be changed. i.e. this code cannot simply be\n * copied and put under another distribution licence\n * [including the GNU Public Licence.]\n */\n\n\nISC license used for completely new code in BoringSSL:\n\n/* Copyright (c) 2015, Google Inc.\n *\n * Permission to use, copy, modify, and/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY\n * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION\n * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN\n * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */\n\n\nThe code in third_party/fiat carries the MIT license:\n\nCopyright (c) 2015-2016 the fiat-crypto authors (see\nhttps://github.com/mit-plv/fiat-crypto/blob/master/AUTHORS).\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n" - package_name: rmp - package_version: 0.8.12 + package_version: 0.8.14 repository: https://github.com/3Hren/msgpack-rust license: MIT licenses: @@ -17110,6 +17110,34 @@ third_party_libraries: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +- package_name: rmpv + package_version: 1.3.0 + repository: https://github.com/3Hren/msgpack-rust + license: MIT + licenses: + - license: MIT + text: | + MIT License + + Copyright (c) 2017 Evgeny Safronov + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE diff --git a/trace-mini-agent/src/env_verifier.rs b/trace-mini-agent/src/env_verifier.rs index 714456de0..8363d224f 100644 --- a/trace-mini-agent/src/env_verifier.rs +++ b/trace-mini-agent/src/env_verifier.rs @@ -139,6 +139,9 @@ impl EnvVerifier for ServerlessEnvVerifier { .verify_gcp_environment_or_exit(verify_env_timeout) .await; } + trace_utils::EnvironmentType::LambdaFunction => { + trace_utils::MiniAgentMetadata::default() + } } } } diff --git a/trace-utils/Cargo.toml b/trace-utils/Cargo.toml index 4ef27bebf..a2e8ea640 100644 --- a/trace-utils/Cargo.toml +++ b/trace-utils/Cargo.toml @@ -25,6 +25,8 @@ rand = "0.8.5" bytes = "1.6.0" # This should only be used for testing. It isn't under dev-dependencies because test-utils can't be under #[cfg(test)]. httpmock = { version = "0.7.0", optional = true} +rmpv = { version = "1.3.0", default-features = false } +rmp = { version = "0.8.14", default-features = false } [dev-dependencies] tokio = { version = "1", features = ["macros", "rt-multi-thread"] } @@ -32,4 +34,4 @@ serde_json = "1.0" httpmock = { version = "0.7.0"} [features] -test-utils = ["httpmock"] \ No newline at end of file +test-utils = ["httpmock"] diff --git a/trace-utils/src/config_utils.rs b/trace-utils/src/config_utils.rs index 6e7f4e533..3095e5800 100644 --- a/trace-utils/src/config_utils.rs +++ b/trace-utils/src/config_utils.rs @@ -10,6 +10,9 @@ const TRACE_INTAKE_ROUTE: &str = "/api/v0.2/traces"; const TRACE_STATS_INTAKE_ROUTE: &str = "/api/v0.2/stats"; pub fn read_cloud_env() -> Option<(String, trace_utils::EnvironmentType)> { + if let Ok(res) = env::var("AWS_LAMBDA_FUNCTION_NAME") { + return Some((res, trace_utils::EnvironmentType::LambdaFunction)); + } if let Ok(res) = env::var("K_SERVICE") { // Set by Google Cloud Functions for newer runtimes return Some((res, trace_utils::EnvironmentType::CloudFunction)); diff --git a/trace-utils/src/trace_utils.rs b/trace-utils/src/trace_utils.rs index f7dbaf98a..9162ab391 100644 --- a/trace-utils/src/trace_utils.rs +++ b/trace-utils/src/trace_utils.rs @@ -1,8 +1,13 @@ // Copyright 2023-Present Datadog, Inc. https://www.datadoghq.com/ // SPDX-License-Identifier: Apache-2.0 +use anyhow::anyhow; +use bytes::buf::Reader; use hyper::{body::Buf, Body}; use log::{error, info}; +use rmp::decode::read_array_len; +use rmpv::decode::read_value; +use rmpv::{Integer, Value}; use std::cmp::Ordering; use std::collections::HashMap; @@ -20,6 +25,8 @@ const TOP_LEVEL_KEY: &str = "_top_level"; const TRACER_TOP_LEVEL_KEY: &str = "_dd.top_level"; const MAX_PAYLOAD_SIZE: usize = 50 * 1024 * 1024; +const MAX_STRING_DICT_SIZE: u32 = 25_000_000; +const SPAN_ELEMENT_COUNT: usize = 12; /// First value of returned tuple is the payload size pub async fn get_traces_from_request_body(body: Body) -> anyhow::Result<(usize, Vec>)> { @@ -40,6 +47,209 @@ pub async fn get_traces_from_request_body(body: Body) -> anyhow::Result<(usize, Ok((size, traces)) } +#[inline] +fn get_v05_strings_dict(reader: &mut Reader) -> anyhow::Result> { + let dict_size = + read_array_len(reader).map_err(|err| anyhow!("Error reading dict size: {err}"))?; + if dict_size > MAX_STRING_DICT_SIZE { + anyhow::bail!( + "Error deserializing strings dictionary. Dict size is too large: {dict_size}" + ); + } + let mut dict: Vec = Vec::with_capacity(dict_size.try_into()?); + for _ in 0..dict_size { + match read_value(reader)? { + Value::String(s) => { + let parsed_string = s.into_str().ok_or_else(|| anyhow!("Error reading string dict"))?; + dict.push(parsed_string); + } + val => anyhow::bail!("Error deserializing strings dictionary. Value in string dict is not a string: {val}") + } + } + Ok(dict) +} + +#[inline] +fn get_v05_span(reader: &mut Reader, dict: &[String]) -> anyhow::Result { + let mut span: Span = Default::default(); + let span_size = rmp::decode::read_array_len(reader) + .map_err(|err| anyhow!("Error reading span size: {err}"))? as usize; + if span_size != SPAN_ELEMENT_COUNT { + anyhow::bail!("Expected an array of exactly 12 elements in a span, got {span_size}"); + } + //0 - service + span.service = get_v05_string(reader, dict, "service")?; + // 1 - name + span.name = get_v05_string(reader, dict, "name")?; + // 2 - resource + span.resource = get_v05_string(reader, dict, "resource")?; + + // 3 - trace_id + match read_value(reader)? { + Value::Integer(i) => { + span.trace_id = i.as_u64().ok_or_else(|| { + anyhow!("Error reading span trace_id, value is not an integer: {i}") + })?; + } + val => anyhow::bail!("Error reading span trace_id, value is not an integer: {val}"), + }; + // 4 - span_id + match read_value(reader)? { + Value::Integer(i) => { + span.span_id = i.as_u64().ok_or_else(|| { + anyhow!("Error reading span span_id, value is not an integer: {i}") + })?; + } + val => anyhow::bail!("Error reading span span_id, value is not an integer: {val}"), + }; + // 5 - parent_id + match read_value(reader)? { + Value::Integer(i) => { + span.parent_id = i.as_u64().ok_or_else(|| { + anyhow!("Error reading span parent_id, value is not an integer: {i}") + })?; + } + val => anyhow::bail!("Error reading span parent_id, value is not an integer: {val}"), + }; + //6 - start + match read_value(reader)? { + Value::Integer(i) => { + span.start = i + .as_i64() + .ok_or_else(|| anyhow!("Error reading span start, value is not an integer: {i}"))?; + } + val => anyhow::bail!("Error reading span start, value is not an integer: {val}"), + }; + //7 - duration + match read_value(reader)? { + Value::Integer(i) => { + span.duration = i.as_i64().ok_or_else(|| { + anyhow!("Error reading span duration, value is not an integer: {i}") + })?; + } + val => anyhow::bail!("Error reading span duration, value is not an integer: {val}"), + }; + //8 - error + match read_value(reader)? { + Value::Integer(i) => { + span.error = i + .as_i64() + .ok_or_else(|| anyhow!("Error reading span error, value is not an integer: {i}"))? + as i32; + } + val => anyhow::bail!("Error reading span error, value is not an integer: {val}"), + } + //9 - meta + match read_value(reader)? { + Value::Map(meta) => { + for (k, v) in meta.iter() { + match k { + Value::Integer(k) => { + match v { + Value::Integer(v) => { + let key = str_from_dict(dict, *k)?; + let val = str_from_dict(dict, *v)?; + span.meta.insert(key, val); + } + _ => anyhow::bail!("Error reading span meta, value is not an integer and can't be looked up in dict: {v}") + } + } + _ => anyhow::bail!("Error reading span meta, key is not an integer and can't be looked up in dict: {k}") + } + } + } + val => anyhow::bail!("Error reading span meta, value is not a map: {val}"), + } + // 10 - metrics + match read_value(reader)? { + Value::Map(metrics) => { + for (k, v) in metrics.iter() { + match k { + Value::Integer(k) => { + match v { + Value::Integer(v) => { + let key = str_from_dict(dict, *k)?; + span.metrics.insert(key, v.as_f64().ok_or_else(||anyhow!("Error reading span metrics, value is not an integer: {v}"))?); + } + Value::F64(v) => { + let key = str_from_dict(dict, *k)?; + span.metrics.insert(key, *v); + } + _ => anyhow::bail!( + "Error reading span metrics, value is not a float or integer: {v}" + ), + } + } + _ => anyhow::bail!("Error reading span metrics, key is not an integer: {k}"), + } + } + } + val => anyhow::bail!("Error reading span metrics, value is not a map: {val}"), + } + + // 11 - type + match read_value(reader)? { + Value::Integer(s) => span.r#type = str_from_dict(dict, s)?, + val => anyhow::bail!("Error reading span type, value is not an integer: {val}"), + } + Ok(span) +} + +#[inline] +fn str_from_dict(dict: &[String], id: Integer) -> anyhow::Result { + let id = id + .as_i64() + .ok_or_else(|| anyhow!("Error reading string from dict, id is not an integer: {id}"))? + as usize; + if id >= dict.len() { + anyhow::bail!("Error reading string from dict, id out of bounds: {id}"); + } + Ok(dict[id].to_string()) +} + +#[inline] +fn get_v05_string( + reader: &mut Reader, + dict: &[String], + field_name: &str, +) -> anyhow::Result { + match read_value(reader)? { + Value::Integer(s) => { + str_from_dict(dict, s) + }, + val => anyhow::bail!("Error reading {field_name}, value is not an integer and can't be looked up in dict: {val}") + } +} + +pub async fn get_v05_traces_from_request_body( + body: Body, +) -> anyhow::Result<(usize, Vec>)> { + let buffer = hyper::body::aggregate(body).await?; + let body_size = buffer.remaining(); + let mut reader = buffer.reader(); + let wrapper_size = read_array_len(&mut reader)?; + if wrapper_size != 2 { + anyhow::bail!("Expected an arrary of exactly 2 elements, got {wrapper_size}"); + } + + let dict = get_v05_strings_dict(&mut reader)?; + + let traces_size = rmp::decode::read_array_len(&mut reader)?; + let mut traces: Vec> = Default::default(); + + for _ in 0..traces_size { + let spans_size = rmp::decode::read_array_len(&mut reader)?; + let mut trace: Vec = Default::default(); + + for _ in 0..spans_size { + let span = get_v05_span(&mut reader, &dict)?; + trace.push(span); + } + traces.push(trace); + } + Ok((body_size, traces)) +} + // Tags gathered from a trace's root span #[derive(Default)] pub struct RootSpanTags<'a> { @@ -217,6 +427,7 @@ pub fn set_serverless_root_span_tags( let origin_tag = match env_type { EnvironmentType::CloudFunction => "cloudfunction", EnvironmentType::AzureFunction => "azurefunction", + EnvironmentType::LambdaFunction => "lambda", // historical reasons }; span.meta .insert("_dd.origin".to_string(), origin_tag.to_string()); @@ -238,6 +449,7 @@ fn update_tracer_top_level(span: &mut Span) { pub enum EnvironmentType { CloudFunction, AzureFunction, + LambdaFunction, } #[derive(Clone, Default, Debug, Eq, PartialEq)] @@ -459,6 +671,88 @@ mod tests { assert!(coalesced.len() > 1 && coalesced.len() < 5); } + #[tokio::test] + #[allow(clippy::type_complexity)] + async fn get_v05_traces_from_request_body() { + let data: ( + Vec, + Vec< + Vec<( + u8, + u8, + u8, + u64, + u64, + u64, + i64, + i64, + i32, + HashMap, + HashMap, + u8, + )>, + >, + ) = ( + vec![ + "baggage".to_string(), + "item".to_string(), + "elasticsearch.version".to_string(), + "7.0".to_string(), + "my-name".to_string(), + "X".to_string(), + "my-service".to_string(), + "my-resource".to_string(), + "_dd.sampling_rate_whatever".to_string(), + "value whatever".to_string(), + "sql".to_string(), + ], + vec![vec![( + 6, + 4, + 7, + 1, + 2, + 3, + 123, + 456, + 1, + HashMap::from([(8, 9), (0, 1), (2, 3)]), + HashMap::from([(5, 1.2)]), + 10, + )]], + ); + let bytes = rmp_serde::to_vec(&data).unwrap(); + let res = + trace_utils::get_v05_traces_from_request_body(hyper::body::Body::from(bytes)).await; + assert!(res.is_ok()); + let (_, traces) = res.unwrap(); + let span = traces[0][0].clone(); + let test_span = Span { + service: "my-service".to_string(), + name: "my-name".to_string(), + resource: "my-resource".to_string(), + trace_id: 1, + span_id: 2, + parent_id: 3, + start: 123, + duration: 456, + error: 1, + meta: HashMap::from([ + ("baggage".to_string(), "item".to_string()), + ("elasticsearch.version".to_string(), "7.0".to_string()), + ( + "_dd.sampling_rate_whatever".to_string(), + "value whatever".to_string(), + ), + ]), + metrics: HashMap::from([("X".to_string(), 1.2)]), + meta_struct: HashMap::default(), + r#type: "sql".to_string(), + span_links: vec![], + }; + assert!(span == test_span); + } + #[tokio::test] #[cfg_attr(miri, ignore)] async fn test_get_traces_from_request_body() {