diff --git a/Cargo.lock b/Cargo.lock index f58fb50797..5020606f8d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1568,6 +1568,7 @@ dependencies = [ "target-triple", "tokio", "tokio-util", + "zstd", ] [[package]] diff --git a/LICENSE-3rdparty.yml b/LICENSE-3rdparty.yml index fbe60d1d51..3acd684748 100644 --- a/LICENSE-3rdparty.yml +++ b/LICENSE-3rdparty.yml @@ -15407,13 +15407,6 @@ 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 diff --git a/datadog-profiling/Cargo.toml b/datadog-profiling/Cargo.toml index b0585e2bff..6e7eea8e64 100644 --- a/datadog-profiling/Cargo.toml +++ b/datadog-profiling/Cargo.toml @@ -32,7 +32,6 @@ hyper = { workspace = true} http-body-util = "0.1" hyper-multipart-rfc7578 = "0.9.0" indexmap = "2.2" -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 } @@ -41,7 +40,9 @@ serde_json = {version = "1.0"} target-triple = "0.1.4" tokio = {version = "1.23", features = ["rt", "macros"]} tokio-util = "0.7.1" +zstd = { version = "0.13", default-features = false } [dev-dependencies] bolero = "0.13" criterion = "0.5.1" +lz4_flex = { version = "0.9", default-features = false, features = ["std", "frame"] } diff --git a/datadog-profiling/src/exporter/mod.rs b/datadog-profiling/src/exporter/mod.rs index 07cac1368f..5d751863ae 100644 --- a/datadog-profiling/src/exporter/mod.rs +++ b/datadog-profiling/src/exporter/mod.rs @@ -1,12 +1,12 @@ // Copyright 2021-Present Datadog, Inc. https://www.datadoghq.com/ // SPDX-License-Identifier: Apache-2.0 +use anyhow::Context; use bytes::Bytes; pub use chrono::{DateTime, Utc}; pub use ddcommon::tag::Tag; pub use hyper::Uri; use hyper_multipart_rfc7578::client::multipart; -use lz4_flex::frame::FrameEncoder; use serde_json::json; use std::borrow::Cow; use std::fmt::Debug; @@ -29,6 +29,7 @@ pub use connector::uds::{socket_path_from_uri, socket_path_to_uri}; pub use connector::named_pipe::{named_pipe_path_from_uri, named_pipe_path_to_uri}; use crate::internal::EncodedProfile; +use crate::profiles::Compressor; const DURATION_ZERO: std::time::Duration = std::time::Duration::from_millis(0); @@ -279,8 +280,10 @@ impl ProfileExporter { // not reserving too much for things that compress really well, and // power-of-two capacities are almost always the best performing. let capacity = (file.bytes.len() / 10).next_power_of_two(); - let buffer = Vec::with_capacity(capacity); - let mut encoder = FrameEncoder::new(buffer); + let max_capacity = 50 * 1024 * 1024; + let compression_level = 1; + let mut encoder = Compressor::try_new(capacity, max_capacity, compression_level) + .context("failed to create compressor")?; encoder.write_all(file.bytes)?; let encoded = encoder.finish()?; /* The Datadog RFC examples strip off the file extension, but the exact behavior diff --git a/datadog-profiling/src/internal/observation/observations.rs b/datadog-profiling/src/internal/observation/observations.rs index 6c4ce372ca..a15e5db97b 100644 --- a/datadog-profiling/src/internal/observation/observations.rs +++ b/datadog-profiling/src/internal/observation/observations.rs @@ -189,7 +189,7 @@ impl IntoIterator for Observations { } } -#[cfg(test)] +#[cfg(all(test, not(miri)))] mod tests { use super::*; use crate::collections::identifiable::*; diff --git a/datadog-profiling/src/internal/observation/timestamped_observations.rs b/datadog-profiling/src/internal/observation/timestamped_observations.rs index df4eca2a7a..6d2e0b10aa 100644 --- a/datadog-profiling/src/internal/observation/timestamped_observations.rs +++ b/datadog-profiling/src/internal/observation/timestamped_observations.rs @@ -11,14 +11,11 @@ use super::super::StackTraceId; use crate::collections::identifiable::Id; use crate::internal::Timestamp; use byteorder::{NativeEndian, ReadBytesExt}; -use lz4_flex::frame::FrameDecoder; -use lz4_flex::frame::FrameEncoder; -use std::io::Cursor; use std::io::Write; +use std::io::{BufReader, Cursor}; -#[derive(Debug)] pub struct TimestampedObservations { - compressed_timestamped_data: FrameEncoder>, + compressed_timestamped_data: zstd::Encoder<'static, Vec>, sample_types_len: usize, } @@ -31,17 +28,22 @@ impl TimestampedObservations { const DEFAULT_BUFFER_SIZE: usize = 1_048_576; pub fn new(sample_types_len: usize) -> Self { + #[allow(clippy::expect_used)] // previous API panic'd implicitly Self { - compressed_timestamped_data: FrameEncoder::new(Vec::with_capacity( - Self::DEFAULT_BUFFER_SIZE, - )), + compressed_timestamped_data: zstd::Encoder::new( + Vec::with_capacity(Self::DEFAULT_BUFFER_SIZE), + 1, + ) + .expect("failed to create zstd encoder"), sample_types_len, } } pub fn with_no_backing_store() -> Self { + #[allow(clippy::expect_used)] // previous API panic'd implicitly Self { - compressed_timestamped_data: FrameEncoder::new(vec![]), + compressed_timestamped_data: zstd::Encoder::new(vec![], 1) + .expect("failed to create zstd encoder"), sample_types_len: 0, } } @@ -72,18 +74,19 @@ impl TimestampedObservations { } pub fn into_iter(self) -> TimestampedObservationsIter { - #[allow(clippy::unwrap_used)] + #[allow(clippy::expect_used, clippy::unwrap_used)] TimestampedObservationsIter { - decoder: FrameDecoder::new(Cursor::new( + decoder: zstd::Decoder::new(Cursor::new( self.compressed_timestamped_data.finish().unwrap(), - )), + )) + .expect("failed to create zstd decoder"), sample_types_len: self.sample_types_len, } } } pub struct TimestampedObservationsIter { - decoder: FrameDecoder>>, + decoder: zstd::Decoder<'static, BufReader>>>, sample_types_len: usize, } diff --git a/datadog-profiling/src/internal/profile/mod.rs b/datadog-profiling/src/internal/profile/mod.rs index 2b4154cfda..d201824ac5 100644 --- a/datadog-profiling/src/internal/profile/mod.rs +++ b/datadog-profiling/src/internal/profile/mod.rs @@ -14,10 +14,10 @@ use crate::collections::identifiable::*; use crate::collections::string_storage::{CachedProfileId, ManagedStringStorage}; use crate::collections::string_table::{self, StringTable}; use crate::iter::{IntoLendingIterator, LendingIterator}; +use crate::profiles::Compressor; use anyhow::Context; use datadog_profiling_protobuf::{self as protobuf, Record, Value, NO_OPT_ZERO, OPT_ZERO}; use interning_api::Generation; -use lz4_flex::frame::FrameEncoder; use std::borrow::Cow; use std::collections::HashMap; use std::io; @@ -342,7 +342,18 @@ impl Profile { // size of 32KiB should definitely outperform starting at zero for // time consumed, allocator pressure, and allocator fragmentation. const INITIAL_PPROF_BUFFER_SIZE: usize = 32 * 1024; - let mut compressor = FrameEncoder::new(Vec::with_capacity(INITIAL_PPROF_BUFFER_SIZE)); + const MAX_PROFILE_SIZE: usize = 50 * 1024 * 1024; + + // When testing on some profiles that can't be shared publicly, + // level 1 provided better compressed files while taking less time + // compared to lz4. + const COMPRESSION_LEVEL: i32 = 1; + let mut compressor = Compressor::try_new( + INITIAL_PPROF_BUFFER_SIZE, + MAX_PROFILE_SIZE, + COMPRESSION_LEVEL, + ) + .context("failed to create compressor")?; let mut encoded_profile = self.encode(&mut compressor, end_time, duration)?; encoded_profile.buffer = compressor.finish()?; @@ -899,7 +910,7 @@ impl Profile { } } -#[cfg(test)] +#[cfg(all(test, not(miri)))] mod api_tests { use super::*; use crate::pprof::test_utils::{roundtrip_to_pprof, sorted_samples, string_table_fetch}; diff --git a/datadog-profiling/src/lib.rs b/datadog-profiling/src/lib.rs index 53e3fa3b60..7ba095f4af 100644 --- a/datadog-profiling/src/lib.rs +++ b/datadog-profiling/src/lib.rs @@ -12,3 +12,4 @@ pub mod exporter; pub mod internal; pub mod iter; pub mod pprof; +mod profiles; diff --git a/datadog-profiling/src/pprof/test_utils.rs b/datadog-profiling/src/pprof/test_utils.rs index 63a2d2638d..0e4e22c75c 100644 --- a/datadog-profiling/src/pprof/test_utils.rs +++ b/datadog-profiling/src/pprof/test_utils.rs @@ -1,13 +1,16 @@ // Copyright 2023-Present Datadog, Inc. https://www.datadoghq.com/ // SPDX-License-Identifier: Apache-2.0 +use anyhow::Context; use datadog_profiling_protobuf::prost_impls::{Profile, Sample}; +use std::io::Cursor; pub fn deserialize_compressed_pprof(encoded: &[u8]) -> anyhow::Result { use prost::Message; use std::io::Read; - let mut decoder = lz4_flex::frame::FrameDecoder::new(encoded); + let mut decoder = + zstd::Decoder::new(Cursor::new(encoded)).context("failed to create zstd decoder")?; let mut buf = Vec::new(); decoder.read_to_end(&mut buf)?; let profile = Profile::decode(buf.as_slice())?; diff --git a/datadog-profiling/src/profiles/compressor.rs b/datadog-profiling/src/profiles/compressor.rs new file mode 100644 index 0000000000..2d47c361fb --- /dev/null +++ b/datadog-profiling/src/profiles/compressor.rs @@ -0,0 +1,110 @@ +// Copyright 2025-Present Datadog, Inc. https://www.datadoghq.com/ +// SPDX-License-Identifier: Apache-2.0 + +use std::io::{self, Write}; + +/// This type wraps a [`Vec`] to provide a [`Write`] interface that has a max +/// capacity that won't be exceeded. Additionally, it gracefully handles +/// out-of-memory conditions instead of panicking (unfortunately not compatible +/// with the `no-panic` crate, though). +pub struct SizeRestrictedBuffer { + vec: Vec, + max_capacity: usize, +} + +impl SizeRestrictedBuffer { + pub fn try_new(size_hint: usize, max_capacity: usize) -> io::Result { + if size_hint > max_capacity { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "size hint shouldn't be larger than max capacity", + )); + } + // Round up to the next power of 2, but don't exceed the max_capacity. + let initial_capacity = size_hint.next_power_of_two().min(max_capacity); + let mut vec = Vec::new(); + vec.try_reserve(initial_capacity)?; + Ok(SizeRestrictedBuffer { vec, max_capacity }) + } + + pub fn as_slice(&self) -> &[u8] { + self.vec.as_slice() + } +} + +impl From for Vec { + fn from(buf: SizeRestrictedBuffer) -> Self { + buf.vec + } +} + +impl Write for SizeRestrictedBuffer { + #[inline] + fn write(&mut self, buf: &[u8]) -> io::Result { + let additional = buf.len(); + if additional <= self.max_capacity.wrapping_sub(self.vec.len()) { + self.vec.try_reserve(additional)?; + self.vec.extend(buf); + Ok(additional) + } else { + Err(io::ErrorKind::StorageFull.into()) + } + } + + #[inline] + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +/// Used to compress profile data. +pub struct Compressor { + encoder: zstd::Encoder<'static, SizeRestrictedBuffer>, +} + +impl Compressor { + /// Creates a new compressor with the provided configuration. + /// + /// - `size_hint`: beginning capacity for the output buffer. This is a hint for the starting + /// size, and the implementation may use something different. + /// - `max_capacity`: the maximum size for the output buffer (hard limit). + /// - `compression_level`: see [`zstd::Encoder::new`] for the valid range. + pub fn try_new( + size_hint: usize, + max_capacity: usize, + compression_level: i32, + ) -> io::Result { + let buffer = SizeRestrictedBuffer::try_new(size_hint, max_capacity)?; + let encoder = + zstd::Encoder::<'static, SizeRestrictedBuffer>::new(buffer, compression_level)?; + Ok(Compressor { encoder }) + } + + /// Finish the compression, and return the compressed data. The compressor + /// remains valid but is missing its encoder, so it will fail to encode + /// data. + /// + /// # Errors + /// + /// 1. Fails if the compressor's encoder is missing. + /// 2. Fails if the encoder fails, e.g., the output buffer is full. + pub fn finish(self) -> io::Result> { + match self.encoder.try_finish() { + Ok(buffer) => Ok(buffer.vec), + Err(err) => Err(err.1), + } + } +} + +impl Write for Compressor { + #[inline] + fn write(&mut self, buf: &[u8]) -> io::Result { + let encoder = &mut self.encoder; + encoder.write(buf) + } + + #[inline] + fn flush(&mut self) -> io::Result<()> { + self.encoder.flush() + } +} diff --git a/datadog-profiling/src/profiles/mod.rs b/datadog-profiling/src/profiles/mod.rs new file mode 100644 index 0000000000..95ba786481 --- /dev/null +++ b/datadog-profiling/src/profiles/mod.rs @@ -0,0 +1,6 @@ +// Copyright 2025-Present Datadog, Inc. https://www.datadoghq.com/ +// SPDX-License-Identifier: Apache-2.0 + +mod compressor; + +pub use compressor::*;