Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions google/cloud/storage/google_cloud_cpp_storage.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down
3 changes: 3 additions & 0 deletions google/cloud/storage/google_cloud_cpp_storage.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::string_view, 9>
inline constexpr std::array<std::string_view, 10>
kStorageLatencyHistogramInstruments = {{
kRequestDurationMetric,
kHttpRequestDurationMetric,
"gcp.storage.client.ttfb",
"rpc.client.call.duration",
"gcp.storage.client.stall.duration",
Expand Down
230 changes: 230 additions & 0 deletions google/cloud/storage/internal/http_attempt_timing_metrics.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,230 @@
// 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 <opentelemetry/common/attribute_value.h>
#include <opentelemetry/common/key_value_iterable_view.h>
#include <opentelemetry/context/context.h>
#include <opentelemetry/nostd/string_view.h>
#include <algorithm>
#include <array>
#include <chrono>
#include <cstddef>
#include <string>
#include <string_view>
#include <utility>

namespace google {
namespace cloud {
namespace storage_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
namespace {

using Attr = std::pair<opentelemetry::nostd::string_view,
opentelemetry::common::AttributeValue>;

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<double>(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<std::string_view, 28> kAllowed = {{
"storage",
"v1",
"upload",
"download",
"b",
"o",
"iam",
"testPermissions",
"acl",
"defaultObjectAcl",
"notificationConfigs",
"hmacKeys",
"projects",
"serviceAccount",
"folders",
"managedFolders",
"anywhereCaches",
"lockRetentionPolicy",
"rewriteTo",
"copyTo",
"moveTo",
"compose",
"restore",
"renameTo",
"operations",
"disable",
"pause",
"resume",
}};
return std::any_of(
kAllowed.begin(), kAllowed.end(),
[segment](std::string_view allowed) { return segment == allowed; });
}
Comment on lines +80 to +114

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

For better readability and consistency, we can include "resume" directly in the kAllowed array instead of checking it separately at the end of the function.

bool IsKnownJsonLiteralSegment(std::string_view segment) {
  constexpr std::array<std::string_view, 28> 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",
      "resume",
  }};
  for (std::string_view allowed : kAllowed) {
    if (segment == allowed) return true;
  }
  return false;
}


// 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) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

To support the overload of ComputeUrlTemplate without the default parameter (adhering to the style guide for internal namespaces), please define both overloads here.

std::string ComputeUrlTemplate(std::string_view path) {
  return ComputeUrlTemplate(path, "");
}

std::string ComputeUrlTemplate(std::string_view path, std::string_view host) {
References
  1. Disallow Default Parameters in internal Namespaces: Reject default argument values in functions, member functions, and constructors declared in internal namespaces (e.g., google::cloud::::internal, google::cloud::_internal). Require all internal callers and unit tests to explicitly supply all arguments. Suggest explicit function overloads if a simpler calling syntax is needed. (link)

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).
// 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 && 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 (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('/');
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 ||
trimmed.find_first_not_of('/', slash) == std::string_view::npos) {
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<Attr, 10> 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.http_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
89 changes: 89 additions & 0 deletions google/cloud/storage/internal/http_attempt_timing_metrics.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
// 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 <opentelemetry/context/context.h>
#include <opentelemetry/metrics/meter.h>
#include <opentelemetry/metrics/meter_provider.h>
#include <opentelemetry/metrics/sync_instruments.h>
#include <opentelemetry/nostd/shared_ptr.h>
#include <opentelemetry/nostd/unique_ptr.h>
#include <chrono>
#include <cstdint>
#include <string>
#include <string_view>

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/...`), full URLs (such as resumable upload session
/// URLs), XML virtual-hosted-style paths
/// (`<bucket>.storage.googleapis.com/<object>`), and XML path-style paths
/// (`/<bucket>/<object>`).
std::string ComputeUrlTemplate(std::string_view path,
std::string_view host = "");
Comment on lines +44 to +45

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

According to the repository style guide, default parameter values are disallowed in internal namespaces (such as google::cloud::storage_internal). Please provide an explicit function overload instead of using a default argument.

std::string ComputeUrlTemplate(std::string_view path);
std::string ComputeUrlTemplate(std::string_view path,
                               std::string_view host);
References
  1. Disallow Default Parameters in internal Namespaces: Reject default argument values in functions, member functions, and constructors declared in internal namespaces (e.g., google::cloud::::internal, google::cloud::_internal). Require all internal callers and unit tests to explicitly supply all arguments. Suggest explicit function overloads if a simpler calling syntax is needed. (link)


/// 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 http_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);

/// 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,
opentelemetry::context::Context const& ctx) const;

private:
std::string client_version_;
std::string server_address_;
opentelemetry::nostd::shared_ptr<opentelemetry::metrics::Meter> meter_;
opentelemetry::nostd::unique_ptr<opentelemetry::metrics::Histogram<double>>
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
Loading
Loading