| // 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 "tracing/scoped_span.h" | |
| #include <memory> | |
| #include <utility> | |
| #include "tracing/span.h" | |
| #include "tracing/thread_context.h" | |
| namespace credentio_tracing { | |
| ScopedSpan::ScopedSpan(Span* span) | |
| : span_(span), previous_span_(ThreadContext::GetCurrentSpan()) { | |
| if (span_) { | |
| ThreadContext::SetCurrentSpan(span_); | |
| } | |
| } | |
| ScopedSpan::ScopedSpan(std::unique_ptr<Span> span) | |
| : owned_span_(std::move(span)), | |
| span_(owned_span_.get()), | |
| previous_span_(ThreadContext::GetCurrentSpan()) { | |
| if (span_) { | |
| ThreadContext::SetCurrentSpan(span_); | |
| } | |
| } | |
| void ScopedSpan::Teardown() { | |
| if (active_) { | |
| if (owned_span_) { | |
| owned_span_->End(); | |
| } | |
| ThreadContext::SetCurrentSpan(previous_span_); | |
| active_ = false; | |
| } | |
| } | |
| ScopedSpan::~ScopedSpan() { Teardown(); } | |
| ScopedSpan::ScopedSpan(ScopedSpan&& other) noexcept | |
| : owned_span_(std::move(other.owned_span_)), | |
| span_(std::exchange(other.span_, nullptr)), | |
| previous_span_(std::exchange(other.previous_span_, nullptr)), | |
| active_(std::exchange(other.active_, false)) { | |
| // NOMUTANTS -- Defensive cleanup; previous_span_ is private and only accessed | |
| // when active_ is true. | |
| } | |
| ScopedSpan& ScopedSpan::operator=(ScopedSpan&& other) noexcept { | |
| if (this != &other) { | |
| Teardown(); | |
| owned_span_ = std::move(other.owned_span_); | |
| span_ = std::exchange(other.span_, nullptr); | |
| // NOMUTANTS -- Defensive cleanup; previous_span_ is private and only | |
| // accessed when active_ is true. | |
| previous_span_ = std::exchange(other.previous_span_, nullptr); | |
| active_ = std::exchange(other.active_, false); | |
| if (active_ && span_) { | |
| ThreadContext::SetCurrentSpan(span_); | |
| } | |
| } | |
| return *this; | |
| } | |
| } // namespace credentio_tracing |