diff --git a/google/cloud/storage/google_cloud_cpp_storage.bzl b/google/cloud/storage/google_cloud_cpp_storage.bzl index 58ee2b8042356..318ff882cc773 100644 --- a/google/cloud/storage/google_cloud_cpp_storage.bzl +++ b/google/cloud/storage/google_cloud_cpp_storage.bzl @@ -45,6 +45,7 @@ google_cloud_cpp_storage_hdrs = [ "iam_policy.h", "idempotency_policy.h", "include_folders_as_prefixes.h", + "internal/attempt_timing_metrics.h", "internal/base64.h", "internal/binary_data_as_debug_string.h", "internal/bucket_access_control_parser.h", @@ -170,6 +171,7 @@ google_cloud_cpp_storage_srcs = [ "hmac_key_metadata.cc", "iam_policy.cc", "idempotency_policy.cc", + "internal/attempt_timing_metrics.cc", "internal/base64.cc", "internal/bucket_access_control_parser.cc", "internal/bucket_acl_requests.cc", diff --git a/google/cloud/storage/google_cloud_cpp_storage.cmake b/google/cloud/storage/google_cloud_cpp_storage.cmake index fbdc5e3649469..bc6303f006ddb 100644 --- a/google/cloud/storage/google_cloud_cpp_storage.cmake +++ b/google/cloud/storage/google_cloud_cpp_storage.cmake @@ -67,6 +67,8 @@ add_library( idempotency_policy.cc idempotency_policy.h include_folders_as_prefixes.h + internal/attempt_timing_metrics.cc + internal/attempt_timing_metrics.h internal/base64.cc internal/base64.h internal/binary_data_as_debug_string.h @@ -433,6 +435,7 @@ if (BUILD_TESTING) hashing_options_test.cc hmac_key_metadata_test.cc idempotency_policy_test.cc + internal/attempt_timing_metrics_test.cc internal/base64_test.cc internal/bucket_acl_requests_test.cc internal/bucket_metadata_cache_test.cc diff --git a/google/cloud/storage/internal/attempt_timing_metrics.cc b/google/cloud/storage/internal/attempt_timing_metrics.cc new file mode 100644 index 0000000000000..13ca99cc0387b --- /dev/null +++ b/google/cloud/storage/internal/attempt_timing_metrics.cc @@ -0,0 +1,118 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "google/cloud/storage/internal/attempt_timing_metrics.h" +#include "google/cloud/version.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace google { +namespace cloud { +namespace storage_internal { +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN +namespace { + +constexpr char const* kStorageMeterName = "gl-cpp"; +constexpr char const* kTtfbMetric = "gcp.storage.client.ttfb"; +constexpr char const* kRpcCallDurationMetric = "rpc.client.call.duration"; + +using Attr = std::pair; + +opentelemetry::nostd::string_view ToNostd(std::string_view sv) { + return opentelemetry::nostd::string_view(sv.data(), sv.size()); +} + +std::string SemanticVersionString() { + return std::to_string(google::cloud::version_major()) + "." + + std::to_string(google::cloud::version_minor()) + "." + + std::to_string(google::cloud::version_patch()); +} + +double DurationToNonNegativeSeconds( + std::chrono::steady_clock::duration elapsed) { + return elapsed < std::chrono::steady_clock::duration::zero() + ? 0.0 + : std::chrono::duration(elapsed).count(); +} + +} // namespace + +AttemptTimingMetrics::AttemptTimingMetrics( + opentelemetry::nostd::shared_ptr< + opentelemetry::metrics::MeterProvider> const& provider, + std::string server_address) + : client_version_(SemanticVersionString()), + server_address_(std::move(server_address)) { + if (!provider) return; + meter_ = + provider->GetMeter(kStorageMeterName, google::cloud::version_string()); + if (!meter_) return; + ttfb_ = meter_->CreateDoubleHistogram( + kTtfbMetric, "Time to first byte of a Storage response.", "s"); + rpc_call_duration_ = meter_->CreateDoubleHistogram( + kRpcCallDurationMetric, "Duration of a single gRPC attempt.", "s"); +} + +void AttemptTimingMetrics::RecordTtfb( + TtfbLabels const& labels, std::chrono::steady_clock::duration elapsed, + opentelemetry::context::Context const& ctx) const { + if (!ttfb_) return; + std::array const attrs{{ + {"gcp.client.version", ToNostd(client_version_)}, + {"gcp.client.artifact", + opentelemetry::nostd::string_view("google-cloud-cpp")}, + {"gcp.client.service", opentelemetry::nostd::string_view("storage")}, + {"server.address", ToNostd(server_address_)}, + {"rpc.system.name", ToNostd(labels.rpc_system)}, + {"gcp.storage.operation", ToNostd(labels.operation)}, + {"network.path", ToNostd(labels.network_path)}, + }}; + ttfb_->Record(DurationToNonNegativeSeconds(elapsed), + opentelemetry::common::MakeKeyValueIterableView(attrs), ctx); +} + +void AttemptTimingMetrics::RecordRpcCallDuration( + RpcCallDurationLabels const& labels, + std::chrono::steady_clock::duration elapsed, + opentelemetry::context::Context const& ctx) const { + if (!rpc_call_duration_) return; + std::array const attrs{{ + {"gcp.client.version", ToNostd(client_version_)}, + {"gcp.client.artifact", + opentelemetry::nostd::string_view("google-cloud-cpp")}, + {"gcp.client.service", opentelemetry::nostd::string_view("storage")}, + {"server.address", ToNostd(server_address_)}, + {"rpc.system.name", opentelemetry::nostd::string_view("grpc")}, + {"rpc.method", ToNostd(labels.rpc_method)}, + {"rpc.response.status_code", ToNostd(labels.status_code)}, + {"error.type", ToNostd(labels.error_type)}, + {"network.path", ToNostd(labels.network_path)}, + }}; + rpc_call_duration_->Record( + DurationToNonNegativeSeconds(elapsed), + opentelemetry::common::MakeKeyValueIterableView(attrs), ctx); +} + +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END +} // namespace storage_internal +} // namespace cloud +} // namespace google diff --git a/google/cloud/storage/internal/attempt_timing_metrics.h b/google/cloud/storage/internal/attempt_timing_metrics.h new file mode 100644 index 0000000000000..4267af8bd78bf --- /dev/null +++ b/google/cloud/storage/internal/attempt_timing_metrics.h @@ -0,0 +1,83 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_ATTEMPT_TIMING_METRICS_H +#define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_ATTEMPT_TIMING_METRICS_H + +#include "google/cloud/storage/version.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace google { +namespace cloud { +namespace storage_internal { +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN + +/// Labels for recording time-to-first-byte (`gcp.storage.client.ttfb`). +struct TtfbLabels { + std::string_view rpc_system; + std::string_view operation; + std::string_view network_path; +}; + +/// Labels for recording per-attempt gRPC call duration +/// (`rpc.client.call.duration`). +struct RpcCallDurationLabels { + std::string_view rpc_method; + std::string_view status_code; + std::string_view error_type; + std::string_view network_path; +}; + +/// Thread-safe recorder for per-attempt timing OpenTelemetry Storage metrics +/// (`gcp.storage.client.ttfb` and `rpc.client.call.duration`). +/// When constructed with a null provider, all methods are no-ops. +class AttemptTimingMetrics { + public: + AttemptTimingMetrics( + opentelemetry::nostd::shared_ptr< + opentelemetry::metrics::MeterProvider> const& provider, + std::string server_address); + + void RecordTtfb(TtfbLabels const& labels, + std::chrono::steady_clock::duration elapsed, + opentelemetry::context::Context const& ctx) const; + + void RecordRpcCallDuration(RpcCallDurationLabels const& labels, + std::chrono::steady_clock::duration elapsed, + opentelemetry::context::Context const& ctx) const; + + private: + std::string client_version_; + std::string server_address_; + opentelemetry::nostd::shared_ptr meter_; + opentelemetry::nostd::unique_ptr> + ttfb_; + opentelemetry::nostd::unique_ptr> + rpc_call_duration_; +}; + +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END +} // namespace storage_internal +} // namespace cloud +} // namespace google + +#endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_ATTEMPT_TIMING_METRICS_H diff --git a/google/cloud/storage/internal/attempt_timing_metrics_test.cc b/google/cloud/storage/internal/attempt_timing_metrics_test.cc new file mode 100644 index 0000000000000..4e5e43fb78bf1 --- /dev/null +++ b/google/cloud/storage/internal/attempt_timing_metrics_test.cc @@ -0,0 +1,290 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "google/cloud/storage/internal/attempt_timing_metrics.h" +#include "google/cloud/testing_util/mock_opentelemetry_metrics.h" +#include "google/cloud/version.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace google { +namespace cloud { +namespace storage_internal { +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN +namespace { + +using ::google::cloud::testing_util::MockHistogram; +using ::google::cloud::testing_util::MockMeter; +using ::google::cloud::testing_util::MockMeterProvider; +using ::testing::_; +using ::testing::ByMove; +using ::testing::DoubleEq; +using ::testing::Eq; +using ::testing::Pair; +using ::testing::Return; +using ::testing::UnorderedElementsAre; + +using HistPtr = + opentelemetry::nostd::unique_ptr>; + +std::map ExtractStringAttrs( + opentelemetry::common::KeyValueIterable const& iterable) { + std::map result; + iterable.ForEachKeyValue( + [&](opentelemetry::nostd::string_view key, + opentelemetry::common::AttributeValue value) noexcept { + if (auto const* sv = + opentelemetry::nostd::get_if( + &value)) { + result.emplace(std::string(key.data(), key.size()), + std::string(sv->data(), sv->size())); + } else { + ADD_FAILURE() << "Unexpected non-string attribute for key: " + << std::string(key.data(), key.size()); + } + return true; + }); + return result; +} + +opentelemetry::nostd::shared_ptr +MakeProvider(opentelemetry::nostd::shared_ptr const& meter) { + auto provider = std::make_shared(); + EXPECT_CALL(*provider, GetMeter) + .WillOnce(Return( + opentelemetry::nostd::shared_ptr( + meter))); + return opentelemetry::nostd::shared_ptr< + opentelemetry::metrics::MeterProvider>(provider); +} + +TEST(AttemptTimingMetricsTest, RecordsTtfbAndRpcCallDurationWithAttributes) { + std::map ttfb_attrs; + auto ttfb = std::make_unique>(); + EXPECT_CALL(*ttfb, Record(DoubleEq(0.125), _, _)) + .WillOnce([&](double, opentelemetry::common::KeyValueIterable const& kv, + opentelemetry::context::Context const& ctx) { + opentelemetry::context::ContextValue const val = + ctx.GetValue("trace_marker"); + auto const* marker = opentelemetry::nostd::get_if(&val); + ASSERT_NE(marker, nullptr); + EXPECT_EQ(*marker, 42); + ttfb_attrs = ExtractStringAttrs(kv); + }); + + std::map rpc_attrs; + auto rpc = std::make_unique>(); + EXPECT_CALL(*rpc, Record(DoubleEq(0.5), _, _)) + .WillOnce([&](double, opentelemetry::common::KeyValueIterable const& kv, + opentelemetry::context::Context const& ctx) { + opentelemetry::context::ContextValue const val = + ctx.GetValue("trace_marker"); + auto const* marker = opentelemetry::nostd::get_if(&val); + ASSERT_NE(marker, nullptr); + EXPECT_EQ(*marker, 42); + rpc_attrs = ExtractStringAttrs(kv); + }); + + opentelemetry::nostd::shared_ptr meter = + std::make_shared(); + EXPECT_CALL(*meter, + CreateDoubleHistogram(Eq("gcp.storage.client.ttfb"), _, Eq("s"))) + .WillOnce(Return(ByMove(HistPtr(ttfb.release())))); + EXPECT_CALL(*meter, + CreateDoubleHistogram(Eq("rpc.client.call.duration"), _, Eq("s"))) + .WillOnce(Return(ByMove(HistPtr(rpc.release())))); + + auto provider = std::make_shared(); + EXPECT_CALL(*provider, GetMeter) +#if OPENTELEMETRY_ABI_VERSION_NO >= 2 + .WillOnce([&](opentelemetry::nostd::string_view scope, + opentelemetry::nostd::string_view scope_version, + opentelemetry::nostd::string_view, + opentelemetry::common::KeyValueIterable const*) { +#else + .WillOnce([&](opentelemetry::nostd::string_view scope, + opentelemetry::nostd::string_view scope_version, + opentelemetry::nostd::string_view) { +#endif + EXPECT_EQ(scope, "gl-cpp"); + EXPECT_EQ(scope_version, google::cloud::version_string()); + return opentelemetry::nostd::shared_ptr( + meter); + }); + + AttemptTimingMetrics metrics( + opentelemetry::nostd::shared_ptr( + provider), + "private.googleapis.com"); + + opentelemetry::context::Context const ctx("trace_marker", std::int64_t{42}); + metrics.RecordTtfb({"http", "ReadObject", "cloudpath"}, + std::chrono::milliseconds(125), ctx); + metrics.RecordRpcCallDuration({"google.storage.v2.Storage/ReadObject", + "CANCELLED", "TIMEOUT", "directpath"}, + std::chrono::milliseconds(500), ctx); + + std::string const expected_version = + std::to_string(google::cloud::version_major()) + "." + + std::to_string(google::cloud::version_minor()) + "." + + std::to_string(google::cloud::version_patch()); + + EXPECT_THAT(ttfb_attrs, UnorderedElementsAre( + Pair("gcp.client.version", expected_version), + Pair("gcp.client.artifact", "google-cloud-cpp"), + Pair("gcp.client.service", "storage"), + Pair("server.address", "private.googleapis.com"), + Pair("rpc.system.name", "http"), + Pair("gcp.storage.operation", "ReadObject"), + Pair("network.path", "cloudpath"))); + + EXPECT_THAT( + rpc_attrs, + UnorderedElementsAre( + Pair("gcp.client.version", expected_version), + Pair("gcp.client.artifact", "google-cloud-cpp"), + Pair("gcp.client.service", "storage"), + Pair("server.address", "private.googleapis.com"), + Pair("rpc.system.name", "grpc"), + Pair("rpc.method", "google.storage.v2.Storage/ReadObject"), + Pair("rpc.response.status_code", "CANCELLED"), + Pair("error.type", "TIMEOUT"), Pair("network.path", "directpath"))); +} + +TEST(AttemptTimingMetricsTest, ClampsNegativeDurationsToZero) { + auto ttfb = std::make_unique>(); + EXPECT_CALL(*ttfb, Record(DoubleEq(0.0), _, _)).Times(1); + + auto rpc = std::make_unique>(); + EXPECT_CALL(*rpc, Record(DoubleEq(0.0), _, _)).Times(1); + + opentelemetry::nostd::shared_ptr meter = + std::make_shared(); + EXPECT_CALL(*meter, + CreateDoubleHistogram(Eq("gcp.storage.client.ttfb"), _, _)) + .WillOnce(Return(ByMove(HistPtr(ttfb.release())))); + EXPECT_CALL(*meter, + CreateDoubleHistogram(Eq("rpc.client.call.duration"), _, _)) + .WillOnce(Return(ByMove(HistPtr(rpc.release())))); + + AttemptTimingMetrics metrics(MakeProvider(meter), "storage.googleapis.com"); + opentelemetry::context::Context const ctx; + metrics.RecordTtfb({"http", "ReadObject", "cloudpath"}, + std::chrono::milliseconds(-5), ctx); + metrics.RecordRpcCallDuration( + {"google.storage.v2.Storage/GetObject", "OK", "OK", "cloudpath"}, + std::chrono::milliseconds(-10), ctx); +} + +TEST(AttemptTimingMetricsTest, NullProviderAndNullMeterAreNoOps) { + AttemptTimingMetrics null_provider(nullptr, "storage.googleapis.com"); + opentelemetry::context::Context const ctx; + null_provider.RecordTtfb({"grpc", "ReadObject", "cloudpath"}, + std::chrono::milliseconds(10), ctx); + null_provider.RecordRpcCallDuration( + {"google.storage.v2.Storage/ReadObject", "OK", "OK", "cloudpath"}, + std::chrono::milliseconds(10), ctx); + + auto provider = std::make_shared(); + EXPECT_CALL(*provider, GetMeter) + .WillOnce(Return( + opentelemetry::nostd::shared_ptr{})); + AttemptTimingMetrics null_meter( + opentelemetry::nostd::shared_ptr( + provider), + "storage.googleapis.com"); + null_meter.RecordTtfb({"grpc", "ReadObject", "cloudpath"}, + std::chrono::milliseconds(10), ctx); + null_meter.RecordRpcCallDuration( + {"google.storage.v2.Storage/ReadObject", "OK", "OK", "cloudpath"}, + std::chrono::milliseconds(10), ctx); +} + +TEST(AttemptTimingMetricsTest, NullAndPartialInstrumentsAreSafe) { + opentelemetry::context::Context const ctx; + + // Both instruments null. + opentelemetry::nostd::shared_ptr empty_meter = + std::make_shared(); + EXPECT_CALL(*empty_meter, CreateDoubleHistogram) + .WillOnce(Return(ByMove(HistPtr{}))) + .WillOnce(Return(ByMove(HistPtr{}))); + AttemptTimingMetrics both_null(MakeProvider(empty_meter), + "storage.googleapis.com"); + both_null.RecordTtfb({"grpc", "ReadObject", "cloudpath"}, + std::chrono::milliseconds(5), ctx); + both_null.RecordRpcCallDuration( + {"google.storage.v2.Storage/ReadObject", "OK", "OK", "cloudpath"}, + std::chrono::milliseconds(5), ctx); + + // Only ttfb_ non-null. + auto ttfb = std::make_unique>(); + EXPECT_CALL(*ttfb, Record(DoubleEq(0.01), _, _)).Times(1); + opentelemetry::nostd::shared_ptr ttfb_only_meter = + std::make_shared(); + EXPECT_CALL(*ttfb_only_meter, + CreateDoubleHistogram(Eq("gcp.storage.client.ttfb"), _, _)) + .WillOnce(Return(ByMove(HistPtr(ttfb.release())))); + EXPECT_CALL(*ttfb_only_meter, + CreateDoubleHistogram(Eq("rpc.client.call.duration"), _, _)) + .WillOnce(Return(ByMove(HistPtr{}))); + AttemptTimingMetrics ttfb_only(MakeProvider(ttfb_only_meter), + "storage.googleapis.com"); + ttfb_only.RecordTtfb({"grpc", "ReadObject", "cloudpath"}, + std::chrono::milliseconds(10), ctx); + ttfb_only.RecordRpcCallDuration( + {"google.storage.v2.Storage/ReadObject", "OK", "OK", "cloudpath"}, + std::chrono::milliseconds(10), ctx); + + // Only rpc_call_duration_ non-null. + auto rpc = std::make_unique>(); + EXPECT_CALL(*rpc, Record(DoubleEq(0.02), _, _)).Times(1); + opentelemetry::nostd::shared_ptr rpc_only_meter = + std::make_shared(); + EXPECT_CALL(*rpc_only_meter, + CreateDoubleHistogram(Eq("gcp.storage.client.ttfb"), _, _)) + .WillOnce(Return(ByMove(HistPtr{}))); + EXPECT_CALL(*rpc_only_meter, + CreateDoubleHistogram(Eq("rpc.client.call.duration"), _, _)) + .WillOnce(Return(ByMove(HistPtr(rpc.release())))); + AttemptTimingMetrics rpc_only(MakeProvider(rpc_only_meter), + "storage.googleapis.com"); + rpc_only.RecordTtfb({"grpc", "ReadObject", "cloudpath"}, + std::chrono::milliseconds(20), ctx); + rpc_only.RecordRpcCallDuration( + {"google.storage.v2.Storage/ReadObject", "OK", "OK", "cloudpath"}, + std::chrono::milliseconds(20), ctx); +} + +} // namespace +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END +} // namespace storage_internal +} // namespace cloud +} // namespace google diff --git a/google/cloud/storage/storage_client_unit_tests.bzl b/google/cloud/storage/storage_client_unit_tests.bzl index de5122cc89529..3206b6fb258ec 100644 --- a/google/cloud/storage/storage_client_unit_tests.bzl +++ b/google/cloud/storage/storage_client_unit_tests.bzl @@ -41,6 +41,7 @@ storage_client_unit_tests = [ "hashing_options_test.cc", "hmac_key_metadata_test.cc", "idempotency_policy_test.cc", + "internal/attempt_timing_metrics_test.cc", "internal/base64_test.cc", "internal/bucket_acl_requests_test.cc", "internal/bucket_metadata_cache_test.cc",