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 @@ -46,6 +46,7 @@ google_cloud_cpp_storage_hdrs = [
"idempotency_policy.h",
"include_folders_as_prefixes.h",
"internal/attempt_metrics.h",
"internal/attempt_timing_metrics.h",
"internal/base64.h",
"internal/binary_data_as_debug_string.h",
"internal/bucket_access_control_parser.h",
Expand Down Expand Up @@ -174,6 +175,7 @@ google_cloud_cpp_storage_srcs = [
"iam_policy.cc",
"idempotency_policy.cc",
"internal/attempt_metrics.cc",
"internal/attempt_timing_metrics.cc",
"internal/base64.cc",
"internal/bucket_access_control_parser.cc",
"internal/bucket_acl_requests.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 @@ -69,6 +69,8 @@ add_library(
include_folders_as_prefixes.h
internal/attempt_metrics.cc
internal/attempt_metrics.h
internal/attempt_timing_metrics.cc
internal/attempt_timing_metrics.h
internal/base64.cc
internal/base64.h
internal/binary_data_as_debug_string.h
Expand Down Expand Up @@ -439,6 +441,7 @@ if (BUILD_TESTING)
hmac_key_metadata_test.cc
idempotency_policy_test.cc
internal/attempt_metrics_test.cc
internal/attempt_timing_metrics_test.cc
internal/base64_test.cc
internal/bucket_acl_requests_test.cc
internal/bucket_metadata_cache_test.cc
Expand Down
132 changes: 132 additions & 0 deletions google/cloud/storage/internal/attempt_timing_metrics.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
// 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/storage/internal/metrics_constants.h"
#include "google/cloud/version.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 <array>
#include <chrono>
#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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Same point as my comment on #16712: ToNostd and SemanticVersionString are now in three places, here, operation_metrics.cc and attempt_metrics.cc.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I moved these into shared metrics_attributes.{h,cc} in #16712. Once #16712 lands, I will rebase this PR onto main and reuse them here.


Replied by cpriti-o11y-agent

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());
}
Comment on lines +41 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

To avoid re-computation on each function call, we should cache the semantic version string in a static variable. To prevent static destruction order issues with non-trivial destructors (like std::string), we can allocate it on the heap using new std::string and return a reference to it.

std::string const& SemanticVersionString() {
  static auto const* const version = new std::string(
      std::to_string(google::cloud::version_major()) + "." +
      std::to_string(google::cloud::version_minor()) + "." +
      std::to_string(google::cloud::version_patch()));
  return *version;
}
References
  1. To avoid re-computation on each function call, cache the result in a static variable. This one-time cost is often preferable to repeated computation, even for seemingly quick operations.
  2. Avoid using function-local static variables with non-trivial destructors (such as std::vector or std::string) to prevent static destruction order issues, in accordance with the Google C++ Style Guide.


double DurationToNonNegativeSeconds(
std::chrono::steady_clock::duration elapsed) {
return elapsed < std::chrono::steady_clock::duration::zero()
? 0.0
: std::chrono::duration<double>(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)) {
Comment on lines +56 to +61

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

Remove the initialization of client_version_ from the constructor since we can use the cached static version directly.

AttemptTimingMetrics::AttemptTimingMetrics(
    opentelemetry::nostd::shared_ptr<
        opentelemetry::metrics::MeterProvider> const& provider,
    std::string server_address)
    : server_address_(std::move(server_address)) {

if (!provider) return;
meter_ =
provider->GetMeter(kStorageMeterName, google::cloud::version_string());
if (!meter_) return;
ttfb_ = meter_->CreateDoubleHistogram(
ToNostd(kTtfbMetric),
"Client-observed time to first response byte or ack for attempts that "
"received a Storage server response.",
"s");
rpc_call_duration_ =
meter_->CreateDoubleHistogram(ToNostd(kRpcCallDurationMetric),
"Duration of a single gRPC attempt.", "s");
}

void AttemptTimingMetrics::RecordGrpcTtfb(
TtfbLabels const& labels, std::chrono::steady_clock::duration elapsed,
opentelemetry::context::Context const& ctx) const {
RecordTtfbImpl("grpc", labels, elapsed, ctx);
}

void AttemptTimingMetrics::RecordHttpTtfb(
TtfbLabels const& labels, std::chrono::steady_clock::duration elapsed,
opentelemetry::context::Context const& ctx) const {
RecordTtfbImpl("http", labels, elapsed, ctx);
}

void AttemptTimingMetrics::RecordTtfbImpl(
std::string_view rpc_system, TtfbLabels const& labels,
std::chrono::steady_clock::duration elapsed,
opentelemetry::context::Context const& ctx) const {
if (!ttfb_) return;
std::array<Attr, 7> 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(rpc_system)},
{"gcp.storage.operation", ToNostd(labels.operation)},
{"network.path", ToNostd(labels.network_path)},
}};
Comment on lines +93 to +102

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

Use the cached static SemanticVersionString() directly instead of the member variable client_version_.

  std::array<Attr, 7> const attrs{{
      {"gcp.client.version", ToNostd(SemanticVersionString())},
      {"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<Attr, 9> 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.rpc_status_code)},
{"error.type", ToNostd(labels.error_type)},
{"network.path", ToNostd(labels.network_path)},
}};
Comment on lines +112 to +123

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

Use the cached static SemanticVersionString() directly instead of the member variable client_version_.

  std::array<Attr, 9> const attrs{{
      {"gcp.client.version", ToNostd(SemanticVersionString())},
      {"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
100 changes: 100 additions & 0 deletions google/cloud/storage/internal/attempt_timing_metrics.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
// 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 <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 <string>
#include <string_view>

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 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 rpc_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);

/// Records client-observed TTFB for a gRPC attempt that received a server
/// response (not called for pre-response failures). For reads and unary
/// RPCs, @p elapsed starts at attempt invocation and ends at the first
/// response message; for writes, @p elapsed starts when the client flushes
/// or finishes sending the request and ends at the first server response.
void RecordGrpcTtfb(TtfbLabels const& labels,
std::chrono::steady_clock::duration elapsed,
opentelemetry::context::Context const& ctx) const;

/// Records client-observed TTFB for an HTTP attempt that received a server
/// response (not called for pre-response failures). For reads and metadata
/// requests, @p elapsed starts at attempt start and ends at the first
/// response byte; for writes, @p elapsed starts when the client finishes
/// sending the request and ends at the first response byte.
void RecordHttpTtfb(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:
void RecordTtfbImpl(std::string_view rpc_system, TtfbLabels const& labels,
std::chrono::steady_clock::duration elapsed,
opentelemetry::context::Context const& ctx) const;

std::string client_version_;
std::string server_address_;
Comment on lines +86 to +87

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

Since the semantic version string is static and can be cached safely on the heap, we do not need to store client_version_ as a member variable in every instance of AttemptTimingMetrics. This reduces the object size and avoids unnecessary copies.

  std::string server_address_;

opentelemetry::nostd::shared_ptr<opentelemetry::metrics::Meter> meter_;
opentelemetry::nostd::unique_ptr<opentelemetry::metrics::Histogram<double>>
ttfb_;
opentelemetry::nostd::unique_ptr<opentelemetry::metrics::Histogram<double>>
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
Loading
Loading