From 59dbcdaa0afe35142946c1efd7fcca00e1baab64 Mon Sep 17 00:00:00 2001 From: cpriti-os Date: Mon, 30 Nov 2026 08:03:18 +0000 Subject: [PATCH 1/4] impl(storage): add HttpAttemptTimingMetrics recorder and URL template normalizer --- .../storage/google_cloud_cpp_storage.bzl | 2 + .../storage/google_cloud_cpp_storage.cmake | 3 + .../internal/grpc/metrics_meter_provider.h | 3 +- .../internal/http_attempt_timing_metrics.cc | 232 ++++++++++++ .../internal/http_attempt_timing_metrics.h | 84 +++++ .../http_attempt_timing_metrics_test.cc | 329 ++++++++++++++++++ .../storage/internal/metrics_constants.h | 2 + .../storage/storage_client_unit_tests.bzl | 1 + 8 files changed, 655 insertions(+), 1 deletion(-) create mode 100644 google/cloud/storage/internal/http_attempt_timing_metrics.cc create mode 100644 google/cloud/storage/internal/http_attempt_timing_metrics.h create mode 100644 google/cloud/storage/internal/http_attempt_timing_metrics_test.cc diff --git a/google/cloud/storage/google_cloud_cpp_storage.bzl b/google/cloud/storage/google_cloud_cpp_storage.bzl index 60c87bd5bf2ea..d255e3e49fd76 100644 --- a/google/cloud/storage/google_cloud_cpp_storage.bzl +++ b/google/cloud/storage/google_cloud_cpp_storage.bzl @@ -80,6 +80,7 @@ google_cloud_cpp_storage_hdrs = [ "internal/hedging_thread_pool.h", "internal/hmac_key_metadata_parser.h", "internal/hmac_key_requests.h", + "internal/http_attempt_timing_metrics.h", "internal/http_response.h", "internal/lifecycle_rule_parser.h", "internal/logging_stub.h", @@ -199,6 +200,7 @@ google_cloud_cpp_storage_srcs = [ "internal/hedged_read_metrics.cc", "internal/hmac_key_metadata_parser.cc", "internal/hmac_key_requests.cc", + "internal/http_attempt_timing_metrics.cc", "internal/http_response.cc", "internal/lifecycle_rule_parser.cc", "internal/logging_stub.cc", diff --git a/google/cloud/storage/google_cloud_cpp_storage.cmake b/google/cloud/storage/google_cloud_cpp_storage.cmake index 92986ae941e67..7a563415ae532 100644 --- a/google/cloud/storage/google_cloud_cpp_storage.cmake +++ b/google/cloud/storage/google_cloud_cpp_storage.cmake @@ -128,6 +128,8 @@ add_library( internal/hmac_key_metadata_parser.h internal/hmac_key_requests.cc internal/hmac_key_requests.h + internal/http_attempt_timing_metrics.cc + internal/http_attempt_timing_metrics.h internal/http_response.cc internal/http_response.h internal/lifecycle_rule_parser.cc @@ -469,6 +471,7 @@ if (BUILD_TESTING) internal/hedged_read_metrics_test.cc internal/hedging_thread_pool_test.cc internal/hmac_key_requests_test.cc + internal/http_attempt_timing_metrics_test.cc internal/http_response_test.cc internal/logging_stub_test.cc internal/make_jwt_assertion_test.cc diff --git a/google/cloud/storage/internal/grpc/metrics_meter_provider.h b/google/cloud/storage/internal/grpc/metrics_meter_provider.h index 2f4ab965a0276..2bd929c087a47 100644 --- a/google/cloud/storage/internal/grpc/metrics_meter_provider.h +++ b/google/cloud/storage/internal/grpc/metrics_meter_provider.h @@ -46,9 +46,10 @@ GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN std::string ChannelCreationLatencyInstrument(); /// Storage SDK latency histogram instruments registered with explicit buckets. -inline constexpr std::array +inline constexpr std::array kStorageLatencyHistogramInstruments = {{ kRequestDurationMetric, + kHttpRequestDurationMetric, "gcp.storage.client.ttfb", "rpc.client.call.duration", "gcp.storage.client.stall.duration", diff --git a/google/cloud/storage/internal/http_attempt_timing_metrics.cc b/google/cloud/storage/internal/http_attempt_timing_metrics.cc new file mode 100644 index 0000000000000..2fa97a252f835 --- /dev/null +++ b/google/cloud/storage/internal/http_attempt_timing_metrics.cc @@ -0,0 +1,232 @@ +// 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/http_attempt_timing_metrics.h" +#include "google/cloud/storage/internal/metrics_constants.h" +#include "google/cloud/version.h" +#include "absl/strings/match.h" +#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 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(); +} + +bool IsJsonApiPath(std::string_view trimmed_path) { + return absl::StartsWith(trimmed_path, "storage/v1/") || + absl::StartsWith(trimmed_path, "upload/storage/v1/") || + absl::StartsWith(trimmed_path, "download/storage/v1/"); +} + +std::string_view PlaceholderForCollection(std::string_view collection) { + if (collection == "b") return "{bucket}"; + if (collection == "o") return "{object}"; + if (collection == "acl" || collection == "defaultObjectAcl") { + return "{entity}"; + } + if (collection == "notificationConfigs") return "{notification}"; + if (collection == "hmacKeys") return "{accessId}"; + if (collection == "projects") return "{project}"; + if (collection == "folders" || collection == "managedFolders") { + return "{folder}"; + } + if (collection == "anywhereCaches") return "{anywhereCacheId}"; + if (collection == "operations") return "{operation}"; + return {}; +} + +bool IsKnownJsonLiteralSegment(std::string_view segment) { + constexpr std::array kAllowed = {{ + "storage", + "v1", + "upload", + "download", + "b", + "o", + "iam", + "testPermissions", + "acl", + "defaultObjectAcl", + "notificationConfigs", + "hmacKeys", + "projects", + "serviceAccount", + "folders", + "managedFolders", + "anywhereCaches", + "lockRetentionPolicy", + "rewriteTo", + "copyTo", + "moveTo", + "compose", + "restore", + "rename", + "operations", + "disable", + "pause", + }}; + for (std::string_view allowed : kAllowed) { + if (segment == allowed) return true; + } + return segment == "resume"; +} + +// Normalizes a JSON API path (without leading '/') into a canonical +// leading-'/' template with bounded cardinality. +std::string NormalizeJsonPath(std::string_view trimmed_path) { + std::string result; + result.reserve(trimmed_path.size() + 1); + std::string_view pending_placeholder; + std::size_t pos = 0; + while (pos < trimmed_path.size()) { + std::size_t const end = trimmed_path.find('/', pos); + std::string_view const segment = end == std::string_view::npos + ? trimmed_path.substr(pos) + : trimmed_path.substr(pos, end - pos); + if (segment.empty()) { + // Collapse consecutive slashes and reset pending placeholder so an empty + // resource segment cannot shift subsequent segments out of phase. + pending_placeholder = {}; + } else { + result.push_back('/'); + if (!pending_placeholder.empty()) { + result.append(pending_placeholder); + pending_placeholder = {}; + } else if (IsKnownJsonLiteralSegment(segment)) { + result.append(segment); + pending_placeholder = PlaceholderForCollection(segment); + } else { + result.append("{segment}"); + } + } + if (end == std::string_view::npos) break; + pos = end + 1; + } + return result; +} + +bool IsVirtualHostedHost(std::string_view host) { + std::size_t const colon = host.find(':'); + if (colon != std::string_view::npos) host = host.substr(0, colon); + constexpr std::string_view kSuffix = ".storage.googleapis.com"; + return host.size() > kSuffix.size() && + absl::EndsWithIgnoreCase(host, kSuffix); +} + +} // namespace + +std::string ComputeUrlTemplate(std::string_view path, std::string_view host) { + std::size_t const sep = path.find_first_of("?#"); + if (sep != std::string_view::npos) path = path.substr(0, sep); + + // Handle full URLs (e.g. resumable upload session URLs passed to RestStub). + std::size_t const scheme_end = path.find("://"); + if (scheme_end != std::string_view::npos) { + std::string_view const after_scheme = path.substr(scheme_end + 3); + std::size_t const path_start = after_scheme.find('/'); + if (host.empty()) { + host = path_start == std::string_view::npos + ? after_scheme + : after_scheme.substr(0, path_start); + } + path = path_start == std::string_view::npos + ? std::string_view{} + : after_scheme.substr(path_start); + } + + std::size_t const first = path.find_first_not_of('/'); + if (first == std::string_view::npos) return "/"; + std::string_view const trimmed = path.substr(first); + + if (IsJsonApiPath(trimmed)) return NormalizeJsonPath(trimmed); + if (IsVirtualHostedHost(host)) return "/{object}"; + std::size_t const slash = trimmed.find('/'); + if (slash == std::string_view::npos || slash + 1 == trimmed.size()) { + return "/{bucket}"; + } + return "/{bucket}/{object}"; +} + +HttpAttemptTimingMetrics::HttpAttemptTimingMetrics( + 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; + http_request_duration_ = meter_->CreateDoubleHistogram( + ToNostd(kHttpRequestDurationMetric), + "Duration of a single HTTP request attempt.", "s"); +} + +void HttpAttemptTimingMetrics::RecordHttpRequestDuration( + HttpRequestDurationLabels const& labels, + std::chrono::steady_clock::duration elapsed, + opentelemetry::context::Context const& ctx) const { + if (!http_request_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("http")}, + {"http.request.method", ToNostd(labels.request_method)}, + {"url.template", ToNostd(labels.url_template)}, + {"http.response.status_code", labels.status_code}, + {"error.type", ToNostd(labels.error_type)}, + {"network.path", ToNostd(labels.network_path)}, + }}; + http_request_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/http_attempt_timing_metrics.h b/google/cloud/storage/internal/http_attempt_timing_metrics.h new file mode 100644 index 0000000000000..2941734e6f570 --- /dev/null +++ b/google/cloud/storage/internal/http_attempt_timing_metrics.h @@ -0,0 +1,84 @@ +// 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_HTTP_ATTEMPT_TIMING_METRICS_H +#define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_HTTP_ATTEMPT_TIMING_METRICS_H + +#include "google/cloud/storage/version.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace google { +namespace cloud { +namespace storage_internal { +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN + +/// Normalizes a Storage HTTP request path into a low-cardinality `url.template` +/// by replacing resource identifiers (bucket, object, entity, etc.) with +/// placeholders. +/// +/// Supports JSON API paths (`/storage/v1/...`, `/upload/storage/v1/...`, +/// `/download/storage/v1/...`), XML virtual-hosted-style paths +/// (`.storage.googleapis.com/`), and XML path-style paths +/// (`//`). +std::string ComputeUrlTemplate(std::string_view path, + std::string_view host = ""); + +/// Labels for recording per-attempt HTTP request duration +/// (`http.client.request.duration`). +struct HttpRequestDurationLabels { + std::string_view request_method; + std::string_view url_template; + std::int64_t status_code = 0; + std::string_view error_type; + std::string_view network_path; +}; + +/// Thread-safe recorder for the `http.client.request.duration` OpenTelemetry +/// Storage histogram. +/// When constructed with a null provider, all methods are no-ops. +class HttpAttemptTimingMetrics { + public: + HttpAttemptTimingMetrics( + opentelemetry::nostd::shared_ptr< + opentelemetry::metrics::MeterProvider> const& provider, + std::string server_address); + + void RecordHttpRequestDuration( + HttpRequestDurationLabels 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> + http_request_duration_; +}; + +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END +} // namespace storage_internal +} // namespace cloud +} // namespace google + +#endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_HTTP_ATTEMPT_TIMING_METRICS_H diff --git a/google/cloud/storage/internal/http_attempt_timing_metrics_test.cc b/google/cloud/storage/internal/http_attempt_timing_metrics_test.cc new file mode 100644 index 0000000000000..651e65a59a37d --- /dev/null +++ b/google/cloud/storage/internal/http_attempt_timing_metrics_test.cc @@ -0,0 +1,329 @@ +// 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/http_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>; + +struct CapturedAttrs { + std::map strings; + std::map ints; +}; + +CapturedAttrs ExtractAttrs( + opentelemetry::common::KeyValueIterable const& iterable) { + CapturedAttrs result; + iterable.ForEachKeyValue( + [&](opentelemetry::nostd::string_view key, + opentelemetry::common::AttributeValue value) noexcept { + std::string const k(key.data(), key.size()); + if (auto const* sv = + opentelemetry::nostd::get_if( + &value)) { + result.strings.emplace(k, std::string(sv->data(), sv->size())); + } else if (auto const* i64 = + opentelemetry::nostd::get_if(&value)) { + result.ints.emplace(k, *i64); + } else { + ADD_FAILURE() << "Unexpected attribute type for key: " << k; + } + 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(ComputeUrlTemplateTest, NormalizesJsonAndXmlPaths) { + struct TestCase { + char const* path; + char const* host; + char const* expected; + } const cases[] = { + {"", "storage.googleapis.com", "/"}, + {"/", "storage.googleapis.com", "/"}, + {"//", "storage.googleapis.com", "/"}, + {"/?prefix=foo", "storage.googleapis.com", "/"}, + // JSON API bucket & object operations (with and without leading '/') + {"/storage/v1/b?project=my-proj", "storage.googleapis.com", + "/storage/v1/b"}, + {"storage/v1/b/my-bucket", "storage.googleapis.com", + "/storage/v1/b/{bucket}"}, + {"upload/storage/v1/b/my-bucket/o?uploadType=resumable", + "storage.googleapis.com", "/upload/storage/v1/b/{bucket}/o"}, + {"https://storage.googleapis.com/upload/storage/v1/b/my-bucket/o" + "?uploadType=resumable&upload_id=abc123", + "", "/upload/storage/v1/b/{bucket}/o"}, + {"https://storage.googleapis.com", "", "/"}, + {"/storage/v1/b/my-bucket", "storage.googleapis.com", + "/storage/v1/b/{bucket}"}, + {"/storage/v1/b/my-bucket/o?prefix=dir/", "storage.googleapis.com", + "/storage/v1/b/{bucket}/o"}, + {"/storage/v1/b/my-bucket/o#frag", "storage.googleapis.com", + "/storage/v1/b/{bucket}/o"}, + {"/storage/v1/b//o/secret-obj", "storage.googleapis.com", + "/storage/v1/b/o/{object}"}, + {"/storage/v1/b/b/o/o", "storage.googleapis.com", + "/storage/v1/b/{bucket}/o/{object}"}, + {"/storage/v1/b/my-bucket/unlisted/raw-id", "storage.googleapis.com", + "/storage/v1/b/{bucket}/{segment}/{segment}"}, + {"/storage/v1/b/my-bucket/o/dir%2Ffile.txt?alt=media", + "storage.googleapis.com", "/storage/v1/b/{bucket}/o/{object}"}, + {"/upload/storage/v1/b/my-bucket/o?uploadType=resumable", + "storage.googleapis.com", "/upload/storage/v1/b/{bucket}/o"}, + {"/download/storage/v1/b/my-bucket/o/obj.bin?alt=media", + "storage.googleapis.com", "/download/storage/v1/b/{bucket}/o/{object}"}, + {"/storage/v1/b/src-b/o/src-o/rewriteTo/b/dst-b/o/dst-o", + "storage.googleapis.com", + "/storage/v1/b/{bucket}/o/{object}/rewriteTo/b/{bucket}/o/{object}"}, + {"/storage/v1/b/src-b/o/src-o/copyTo/b/dst-b/o/dst-o", + "storage.googleapis.com", + "/storage/v1/b/{bucket}/o/{object}/copyTo/b/{bucket}/o/{object}"}, + {"/storage/v1/b/my-bucket/o/src-o/moveTo/o/dst-o", + "storage.googleapis.com", + "/storage/v1/b/{bucket}/o/{object}/moveTo/o/{object}"}, + {"/storage/v1/b/my-bucket/o/obj/compose", "storage.googleapis.com", + "/storage/v1/b/{bucket}/o/{object}/compose"}, + {"/storage/v1/b/my-bucket/iam", "storage.googleapis.com", + "/storage/v1/b/{bucket}/iam"}, + {"/storage/v1/b/my-bucket/acl/allUsers", "storage.googleapis.com", + "/storage/v1/b/{bucket}/acl/{entity}"}, + {"/storage/v1/b/my-bucket/defaultObjectAcl/user-a@example.com", + "storage.googleapis.com", + "/storage/v1/b/{bucket}/defaultObjectAcl/{entity}"}, + {"/storage/v1/b/my-bucket/notificationConfigs/42", + "storage.googleapis.com", + "/storage/v1/b/{bucket}/notificationConfigs/{notification}"}, + {"/storage/v1/projects/my-proj/hmacKeys/GOOG1234", + "storage.googleapis.com", + "/storage/v1/projects/{project}/hmacKeys/{accessId}"}, + {"/storage/v1/projects/my-proj/serviceAccount", "storage.googleapis.com", + "/storage/v1/projects/{project}/serviceAccount"}, + {"/storage/v1/b/my-bucket/folders/a%2Fb", "storage.googleapis.com", + "/storage/v1/b/{bucket}/folders/{folder}"}, + {"/storage/v1/b/my-bucket/managedFolders/a%2Fb", "storage.googleapis.com", + "/storage/v1/b/{bucket}/managedFolders/{folder}"}, + {"/storage/v1/b/my-bucket/anywhereCaches/cache-1", + "storage.googleapis.com", + "/storage/v1/b/{bucket}/anywhereCaches/{anywhereCacheId}"}, + {"/storage/v1/b/my-bucket/operations/op-123", "storage.googleapis.com", + "/storage/v1/b/{bucket}/operations/{operation}"}, + // XML API path-style (with and without leading '/') + {"/my-bucket", "storage.googleapis.com", "/{bucket}"}, + {"my-bucket/dir/file.txt", "storage.googleapis.com", + "/{bucket}/{object}"}, + {"/my-bucket/", "storage.googleapis.com", "/{bucket}"}, + {"/my-bucket/dir/file.txt?generation=1", "storage.googleapis.com", + "/{bucket}/{object}"}, + {"/my-bucket/dir/file.txt", ".storage.googleapis.com", + "/{bucket}/{object}"}, + // XML API virtual-hosted style (case-insensitive) + {"/dir/file.txt", "my-bucket.storage.googleapis.com", "/{object}"}, + {"/dir/file.txt", "my-bucket.STORAGE.GOOGLEAPIS.COM:443", "/{object}"}, + {"https://my-bucket.storage.googleapis.com/dir/file.txt", "", + "/{object}"}, + {"/", "my-bucket.storage.googleapis.com", "/"}, + }; + for (TestCase const& c : cases) { + EXPECT_EQ(ComputeUrlTemplate(c.path, c.host), c.expected) + << "path=" << c.path << ", host=" << c.host; + } +} + +TEST(HttpAttemptTimingMetricsTest, RecordsHttpRequestDurationWithAttributes) { + CapturedAttrs recorded; + auto hist = std::make_unique>(); + EXPECT_CALL(*hist, Record(DoubleEq(0.375), _, _)) + .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); + recorded = ExtractAttrs(kv); + }); + + CapturedAttrs no_response; + EXPECT_CALL(*hist, Record(DoubleEq(0.1), _, _)) + .WillOnce([&](double, opentelemetry::common::KeyValueIterable const& kv, + opentelemetry::context::Context const&) { + no_response = ExtractAttrs(kv); + }); + + opentelemetry::nostd::shared_ptr meter = + std::make_shared(); + EXPECT_CALL(*meter, CreateDoubleHistogram(Eq("http.client.request.duration"), + _, Eq("s"))) + .WillOnce(Return(ByMove(HistPtr(hist.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); + }); + + HttpAttemptTimingMetrics metrics( + opentelemetry::nostd::shared_ptr( + provider), + "private.googleapis.com"); + + opentelemetry::context::Context const ctx("trace_marker", std::int64_t{42}); + metrics.RecordHttpRequestDuration({"PUT", "/upload/storage/v1/b/{bucket}/o", + 503, "UNAVAILABLE", "cloudpath"}, + std::chrono::milliseconds(375), ctx); + metrics.RecordHttpRequestDuration({"GET", "/storage/v1/b/{bucket}/o/{object}", + 0, "CONNECTION_ERROR", "cloudpath"}, + std::chrono::milliseconds(100), 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( + recorded.strings, + 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("http.request.method", "PUT"), + Pair("url.template", "/upload/storage/v1/b/{bucket}/o"), + Pair("error.type", "UNAVAILABLE"), + Pair("network.path", "cloudpath"))); + EXPECT_THAT(recorded.ints, + UnorderedElementsAre(Pair("http.response.status_code", 503))); + + EXPECT_THAT(no_response.ints, + UnorderedElementsAre(Pair("http.response.status_code", 0))); + EXPECT_EQ(no_response.strings["error.type"], "CONNECTION_ERROR"); +} + +TEST(HttpAttemptTimingMetricsTest, ClampsNegativeAndRecordsZeroDurations) { + auto hist = std::make_unique>(); + EXPECT_CALL(*hist, Record(DoubleEq(0.0), _, _)).Times(2); + + opentelemetry::nostd::shared_ptr meter = + std::make_shared(); + EXPECT_CALL(*meter, + CreateDoubleHistogram(Eq("http.client.request.duration"), _, _)) + .WillOnce(Return(ByMove(HistPtr(hist.release())))); + + HttpAttemptTimingMetrics metrics(MakeProvider(meter), + "storage.googleapis.com"); + opentelemetry::context::Context const ctx; + metrics.RecordHttpRequestDuration( + {"GET", "/storage/v1/b/{bucket}/o/{object}", 200, "OK", "cloudpath"}, + std::chrono::milliseconds(-5), ctx); + metrics.RecordHttpRequestDuration( + {"GET", "/storage/v1/b/{bucket}/o/{object}", 200, "OK", "cloudpath"}, + std::chrono::milliseconds(0), ctx); +} + +TEST(HttpAttemptTimingMetricsTest, + NullProviderNullMeterAndNullInstrumentAreNoOps) { + opentelemetry::context::Context const ctx; + HttpRequestDurationLabels const labels{ + "GET", "/storage/v1/b/{bucket}/o/{object}", 200, "OK", "cloudpath"}; + + HttpAttemptTimingMetrics null_provider(nullptr, "storage.googleapis.com"); + null_provider.RecordHttpRequestDuration(labels, std::chrono::milliseconds(10), + ctx); + + auto null_meter_provider = std::make_shared(); + EXPECT_CALL(*null_meter_provider, GetMeter) + .WillOnce(Return( + opentelemetry::nostd::shared_ptr{})); + HttpAttemptTimingMetrics null_meter( + opentelemetry::nostd::shared_ptr( + null_meter_provider), + "storage.googleapis.com"); + null_meter.RecordHttpRequestDuration(labels, std::chrono::milliseconds(10), + ctx); + + opentelemetry::nostd::shared_ptr empty_meter = + std::make_shared(); + EXPECT_CALL(*empty_meter, CreateDoubleHistogram) + .WillOnce(Return(ByMove(HistPtr{}))); + HttpAttemptTimingMetrics null_instrument(MakeProvider(empty_meter), + "storage.googleapis.com"); + null_instrument.RecordHttpRequestDuration(labels, + std::chrono::milliseconds(10), ctx); +} + +} // namespace +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END +} // namespace storage_internal +} // namespace cloud +} // namespace google diff --git a/google/cloud/storage/internal/metrics_constants.h b/google/cloud/storage/internal/metrics_constants.h index 11c2e9f135cd9..9f1dde05af6e7 100644 --- a/google/cloud/storage/internal/metrics_constants.h +++ b/google/cloud/storage/internal/metrics_constants.h @@ -34,6 +34,8 @@ inline constexpr char const* kStorageMeterName = "gl-cpp"; /// Shared OpenTelemetry instrument names referenced by both recorders and /// exporter/view registration so they cannot drift apart. +inline constexpr std::string_view kHttpRequestDurationMetric = + "http.client.request.duration"; inline constexpr std::string_view kOperationsMetric = "gcp.storage.client.operations"; inline constexpr std::string_view kRequestDurationMetric = diff --git a/google/cloud/storage/storage_client_unit_tests.bzl b/google/cloud/storage/storage_client_unit_tests.bzl index a44c574c861ba..80ac124d82244 100644 --- a/google/cloud/storage/storage_client_unit_tests.bzl +++ b/google/cloud/storage/storage_client_unit_tests.bzl @@ -72,6 +72,7 @@ storage_client_unit_tests = [ "internal/hedged_read_metrics_test.cc", "internal/hedging_thread_pool_test.cc", "internal/hmac_key_requests_test.cc", + "internal/http_attempt_timing_metrics_test.cc", "internal/http_response_test.cc", "internal/logging_stub_test.cc", "internal/make_jwt_assertion_test.cc", From 9b96740fb4b65bb6e1db8f6a7b1913476d18883c Mon Sep 17 00:00:00 2001 From: cpriti-os Date: Tue, 1 Dec 2026 05:19:42 +0000 Subject: [PATCH 2/4] Rename status_code to http_status_code and document RecordHttpRequestDuration --- .../cloud/storage/internal/http_attempt_timing_metrics.cc | 2 +- google/cloud/storage/internal/http_attempt_timing_metrics.h | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/google/cloud/storage/internal/http_attempt_timing_metrics.cc b/google/cloud/storage/internal/http_attempt_timing_metrics.cc index 2fa97a252f835..eb3aa84f699e0 100644 --- a/google/cloud/storage/internal/http_attempt_timing_metrics.cc +++ b/google/cloud/storage/internal/http_attempt_timing_metrics.cc @@ -217,7 +217,7 @@ void HttpAttemptTimingMetrics::RecordHttpRequestDuration( {"rpc.system.name", opentelemetry::nostd::string_view("http")}, {"http.request.method", ToNostd(labels.request_method)}, {"url.template", ToNostd(labels.url_template)}, - {"http.response.status_code", labels.status_code}, + {"http.response.status_code", labels.http_status_code}, {"error.type", ToNostd(labels.error_type)}, {"network.path", ToNostd(labels.network_path)}, }}; diff --git a/google/cloud/storage/internal/http_attempt_timing_metrics.h b/google/cloud/storage/internal/http_attempt_timing_metrics.h index 2941734e6f570..4349d8ccaaa13 100644 --- a/google/cloud/storage/internal/http_attempt_timing_metrics.h +++ b/google/cloud/storage/internal/http_attempt_timing_metrics.h @@ -48,7 +48,7 @@ std::string ComputeUrlTemplate(std::string_view path, struct HttpRequestDurationLabels { std::string_view request_method; std::string_view url_template; - std::int64_t status_code = 0; + std::int64_t http_status_code = 0; std::string_view error_type; std::string_view network_path; }; @@ -63,6 +63,10 @@ class HttpAttemptTimingMetrics { opentelemetry::metrics::MeterProvider> const& provider, std::string server_address); + /// Records the duration of a single HTTP request attempt (`elapsed` spans + /// from request start until the response body finishes or closes, or until + /// the request fails). Callers should leave `labels.http_status_code` as `0` + /// when no HTTP response was received. void RecordHttpRequestDuration( HttpRequestDurationLabels const& labels, std::chrono::steady_clock::duration elapsed, From 195010ecde5c7a3b67621d218501b3db1c5aef5a Mon Sep 17 00:00:00 2001 From: cpriti-os Date: Tue, 1 Dec 2026 05:33:08 +0000 Subject: [PATCH 3/4] Harden ComputeUrlTemplate edge cases and expand unit tests --- .../internal/http_attempt_timing_metrics.cc | 24 +++++------ .../internal/http_attempt_timing_metrics.h | 3 +- .../http_attempt_timing_metrics_test.cc | 42 ++++++++++++++++++- 3 files changed, 53 insertions(+), 16 deletions(-) diff --git a/google/cloud/storage/internal/http_attempt_timing_metrics.cc b/google/cloud/storage/internal/http_attempt_timing_metrics.cc index eb3aa84f699e0..3912b9ba6fa63 100644 --- a/google/cloud/storage/internal/http_attempt_timing_metrics.cc +++ b/google/cloud/storage/internal/http_attempt_timing_metrics.cc @@ -77,7 +77,7 @@ std::string_view PlaceholderForCollection(std::string_view collection) { } bool IsKnownJsonLiteralSegment(std::string_view segment) { - constexpr std::array kAllowed = {{ + constexpr std::array kAllowed = {{ "storage", "v1", "upload", @@ -101,15 +101,16 @@ bool IsKnownJsonLiteralSegment(std::string_view segment) { "moveTo", "compose", "restore", - "rename", + "renameTo", "operations", "disable", "pause", + "resume", }}; for (std::string_view allowed : kAllowed) { if (segment == allowed) return true; } - return segment == "resume"; + return false; } // Normalizes a JSON API path (without leading '/') into a canonical @@ -161,18 +162,14 @@ std::string ComputeUrlTemplate(std::string_view path, std::string_view host) { if (sep != std::string_view::npos) path = path.substr(0, sep); // Handle full URLs (e.g. resumable upload session URLs passed to RestStub). + // Only treat `://` as a scheme when it appears before the first `/`. std::size_t const scheme_end = path.find("://"); - if (scheme_end != std::string_view::npos) { + if (scheme_end != std::string_view::npos && scheme_end < path.find('/')) { std::string_view const after_scheme = path.substr(scheme_end + 3); std::size_t const path_start = after_scheme.find('/'); - if (host.empty()) { - host = path_start == std::string_view::npos - ? after_scheme - : after_scheme.substr(0, path_start); - } - path = path_start == std::string_view::npos - ? std::string_view{} - : after_scheme.substr(path_start); + if (path_start == std::string_view::npos) return "/"; + if (host.empty()) host = after_scheme.substr(0, path_start); + path = after_scheme.substr(path_start); } std::size_t const first = path.find_first_not_of('/'); @@ -182,7 +179,8 @@ std::string ComputeUrlTemplate(std::string_view path, std::string_view host) { if (IsJsonApiPath(trimmed)) return NormalizeJsonPath(trimmed); if (IsVirtualHostedHost(host)) return "/{object}"; std::size_t const slash = trimmed.find('/'); - if (slash == std::string_view::npos || slash + 1 == trimmed.size()) { + if (slash == std::string_view::npos || + trimmed.find_first_not_of('/', slash) == std::string_view::npos) { return "/{bucket}"; } return "/{bucket}/{object}"; diff --git a/google/cloud/storage/internal/http_attempt_timing_metrics.h b/google/cloud/storage/internal/http_attempt_timing_metrics.h index 4349d8ccaaa13..802d945e35b9f 100644 --- a/google/cloud/storage/internal/http_attempt_timing_metrics.h +++ b/google/cloud/storage/internal/http_attempt_timing_metrics.h @@ -37,7 +37,8 @@ GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN /// placeholders. /// /// Supports JSON API paths (`/storage/v1/...`, `/upload/storage/v1/...`, -/// `/download/storage/v1/...`), XML virtual-hosted-style paths +/// `/download/storage/v1/...`), full URLs (such as resumable upload session +/// URLs), XML virtual-hosted-style paths /// (`.storage.googleapis.com/`), and XML path-style paths /// (`//`). std::string ComputeUrlTemplate(std::string_view path, diff --git a/google/cloud/storage/internal/http_attempt_timing_metrics_test.cc b/google/cloud/storage/internal/http_attempt_timing_metrics_test.cc index 651e65a59a37d..30437beec2a21 100644 --- a/google/cloud/storage/internal/http_attempt_timing_metrics_test.cc +++ b/google/cloud/storage/internal/http_attempt_timing_metrics_test.cc @@ -144,6 +144,15 @@ TEST(ComputeUrlTemplateTest, NormalizesJsonAndXmlPaths) { "/storage/v1/b/{bucket}/o/{object}/compose"}, {"/storage/v1/b/my-bucket/iam", "storage.googleapis.com", "/storage/v1/b/{bucket}/iam"}, + {"/storage/v1/b/my-bucket/iam/testPermissions", "storage.googleapis.com", + "/storage/v1/b/{bucket}/iam/testPermissions"}, + {"/storage/v1/b/my-bucket/lockRetentionPolicy", "storage.googleapis.com", + "/storage/v1/b/{bucket}/lockRetentionPolicy"}, + {"/storage/v1/b/my-bucket/o/obj/restore", "storage.googleapis.com", + "/storage/v1/b/{bucket}/o/{object}/restore"}, + {"/storage/v1/b/my-bucket/folders/src/renameTo/folders/dst", + "storage.googleapis.com", + "/storage/v1/b/{bucket}/folders/{folder}/renameTo/folders/{folder}"}, {"/storage/v1/b/my-bucket/acl/allUsers", "storage.googleapis.com", "/storage/v1/b/{bucket}/acl/{entity}"}, {"/storage/v1/b/my-bucket/defaultObjectAcl/user-a@example.com", @@ -164,6 +173,15 @@ TEST(ComputeUrlTemplateTest, NormalizesJsonAndXmlPaths) { {"/storage/v1/b/my-bucket/anywhereCaches/cache-1", "storage.googleapis.com", "/storage/v1/b/{bucket}/anywhereCaches/{anywhereCacheId}"}, + {"/storage/v1/b/my-bucket/anywhereCaches/cache-1/disable", + "storage.googleapis.com", + "/storage/v1/b/{bucket}/anywhereCaches/{anywhereCacheId}/disable"}, + {"/storage/v1/b/my-bucket/anywhereCaches/cache-1/pause", + "storage.googleapis.com", + "/storage/v1/b/{bucket}/anywhereCaches/{anywhereCacheId}/pause"}, + {"/storage/v1/b/my-bucket/anywhereCaches/cache-1/resume", + "storage.googleapis.com", + "/storage/v1/b/{bucket}/anywhereCaches/{anywhereCacheId}/resume"}, {"/storage/v1/b/my-bucket/operations/op-123", "storage.googleapis.com", "/storage/v1/b/{bucket}/operations/{operation}"}, // XML API path-style (with and without leading '/') @@ -171,6 +189,9 @@ TEST(ComputeUrlTemplateTest, NormalizesJsonAndXmlPaths) { {"my-bucket/dir/file.txt", "storage.googleapis.com", "/{bucket}/{object}"}, {"/my-bucket/", "storage.googleapis.com", "/{bucket}"}, + {"/my-bucket//", "storage.googleapis.com", "/{bucket}"}, + {"/my-bucket/http://example.com/obj", "storage.googleapis.com", + "/{bucket}/{object}"}, {"/my-bucket/dir/file.txt?generation=1", "storage.googleapis.com", "/{bucket}/{object}"}, {"/my-bucket/dir/file.txt", ".storage.googleapis.com", @@ -180,6 +201,8 @@ TEST(ComputeUrlTemplateTest, NormalizesJsonAndXmlPaths) { {"/dir/file.txt", "my-bucket.STORAGE.GOOGLEAPIS.COM:443", "/{object}"}, {"https://my-bucket.storage.googleapis.com/dir/file.txt", "", "/{object}"}, + {"https://my-bucket.storage.googleapis.com/dir/file.txt", + "storage.googleapis.com", "/{bucket}/{object}"}, {"/", "my-bucket.storage.googleapis.com", "/"}, }; for (TestCase const& c : cases) { @@ -205,7 +228,12 @@ TEST(HttpAttemptTimingMetricsTest, RecordsHttpRequestDurationWithAttributes) { CapturedAttrs no_response; EXPECT_CALL(*hist, Record(DoubleEq(0.1), _, _)) .WillOnce([&](double, opentelemetry::common::KeyValueIterable const& kv, - opentelemetry::context::Context const&) { + 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); no_response = ExtractAttrs(kv); }); @@ -265,9 +293,19 @@ TEST(HttpAttemptTimingMetricsTest, RecordsHttpRequestDurationWithAttributes) { EXPECT_THAT(recorded.ints, UnorderedElementsAre(Pair("http.response.status_code", 503))); + EXPECT_THAT( + no_response.strings, + 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("http.request.method", "GET"), + Pair("url.template", "/storage/v1/b/{bucket}/o/{object}"), + Pair("error.type", "CONNECTION_ERROR"), + Pair("network.path", "cloudpath"))); EXPECT_THAT(no_response.ints, UnorderedElementsAre(Pair("http.response.status_code", 0))); - EXPECT_EQ(no_response.strings["error.type"], "CONNECTION_ERROR"); } TEST(HttpAttemptTimingMetricsTest, ClampsNegativeAndRecordsZeroDurations) { From 1e60fa553642c54a2cdbddaf2ff3a783a5b877e1 Mon Sep 17 00:00:00 2001 From: cpriti-os Date: Tue, 1 Dec 2026 09:08:16 +0000 Subject: [PATCH 4/4] Use std::any_of in IsKnownJsonLiteralSegment (clang-tidy) --- .../cloud/storage/internal/http_attempt_timing_metrics.cc | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/google/cloud/storage/internal/http_attempt_timing_metrics.cc b/google/cloud/storage/internal/http_attempt_timing_metrics.cc index 3912b9ba6fa63..3169f74a73502 100644 --- a/google/cloud/storage/internal/http_attempt_timing_metrics.cc +++ b/google/cloud/storage/internal/http_attempt_timing_metrics.cc @@ -20,6 +20,7 @@ #include #include #include +#include #include #include #include @@ -107,10 +108,9 @@ bool IsKnownJsonLiteralSegment(std::string_view segment) { "pause", "resume", }}; - for (std::string_view allowed : kAllowed) { - if (segment == allowed) return true; - } - return false; + return std::any_of( + kAllowed.begin(), kAllowed.end(), + [segment](std::string_view allowed) { return segment == allowed; }); } // Normalizes a JSON API path (without leading '/') into a canonical