Repository navigation
impl(storage): add HttpAttemptTimingMetrics recorder and URL template normalizer #16723
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
59dbcda
9b96740
195010e
1e60fa5
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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; }); | ||
| } | ||
|
|
||
| // 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) { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. To support the overload of std::string ComputeUrlTemplate(std::string_view path) {
return ComputeUrlTemplate(path, "");
}
std::string ComputeUrlTemplate(std::string_view path, std::string_view host) {References
|
||
| 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 | ||
| 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
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. According to the repository style guide, default parameter values are disallowed in internal namespaces (such as std::string ComputeUrlTemplate(std::string_view path);
std::string ComputeUrlTemplate(std::string_view path,
std::string_view host);References
|
||
|
|
||
| /// 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 | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
For better readability and consistency, we can include
"resume"directly in thekAllowedarray instead of checking it separately at the end of the function.