| // 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 THIRD_PARTY_CREDENTIO_TRACING_SCOPED_SPAN_H_ | |
| #define THIRD_PARTY_CREDENTIO_TRACING_SCOPED_SPAN_H_ | |
| #include <memory> | |
| #include "absl/status/status.h" | |
| #include "tracing/span.h" | |
| namespace credentio_tracing { | |
| // RAII container for managing Span object lifetimes and thread-local stack | |
| // binding. | |
| // | |
| // Automatically calls End() on the wrapped Span when ScopedSpan is destroyed, | |
| // unless ownership has been moved, and maintains the implicit parent-child span | |
| // hierarchy on the current thread. | |
| class ScopedSpan { | |
| public: | |
| // Binds an existing Span pointer as active in ThreadContext for this scope. | |
| explicit ScopedSpan(Span* span); | |
| // Wraps an existing Span unique pointer and sets it as active in | |
| // ThreadContext. | |
| explicit ScopedSpan(std::unique_ptr<Span> span); | |
| // Automatically invokes End() on the contained span (if owned) and restores | |
| // the previous active span upon destruction. | |
| ~ScopedSpan(); | |
| ScopedSpan(ScopedSpan&& other) noexcept; | |
| ScopedSpan& operator=(ScopedSpan&& other) noexcept; | |
| ScopedSpan(const ScopedSpan&) = delete; | |
| ScopedSpan& operator=(const ScopedSpan&) = delete; | |
| // Returns a raw pointer to the underlying Span without releasing ownership. | |
| Span* get() const { return span_; } | |
| // Member access operator forwarding calls to the underlying Span. | |
| Span* operator->() const { return span_; } | |
| // Convenience method to set status on the underlying span if valid. | |
| void SetStatus(const absl::Status& status) { | |
| if (span_) { | |
| span_->SetStatus(status); | |
| } | |
| } | |
| private: | |
| void Teardown(); | |
| std::unique_ptr<Span> owned_span_; | |
| Span* span_ = nullptr; | |
| Span* previous_span_ = nullptr; | |
| bool active_ = true; | |
| }; | |
| } // namespace credentio_tracing | |
| #endif // THIRD_PARTY_CREDENTIO_TRACING_SCOPED_SPAN_H_ |