| // 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_TRACER_FACTORY_H_ | |
| #define THIRD_PARTY_CREDENTIO_TRACING_SCOPED_TRACER_FACTORY_H_ | |
| #include <memory> | |
| #include "absl/base/nullability.h" | |
| #include "tracing/tracer_factory.h" | |
| namespace credentio_tracing { | |
| // RAII guard that installs a TracerFactory for the current thread during its | |
| // lifetime and restores the previous one upon destruction. | |
| // | |
| // Installing and clearing a thread-local factory by hand is error prone: the | |
| // two calls must run on the same thread, which is easy to get wrong when the | |
| // work in between hops to a callback or a dispatch queue. This guard makes | |
| // that mistake unrepresentable for synchronous scopes. | |
| // | |
| // It only covers work performed on the calling thread. To scope tracing to an | |
| // asynchronous operation, carry the factory on the operation's | |
| // `credentio::AsyncContext` instead. | |
| class ScopedTracerFactory { | |
| public: | |
| // Installs `factory` as the calling thread's factory. | |
| explicit ScopedTracerFactory( | |
| absl_nullable std::shared_ptr<TracerFactory> factory); | |
| // Restores the previously installed thread-local factory. | |
| ~ScopedTracerFactory(); | |
| ScopedTracerFactory(const ScopedTracerFactory&) = delete; | |
| ScopedTracerFactory& operator=(const ScopedTracerFactory&) = delete; | |
| ScopedTracerFactory(ScopedTracerFactory&&) = delete; | |
| ScopedTracerFactory& operator=(ScopedTracerFactory&&) = delete; | |
| private: | |
| absl_nullable std::shared_ptr<TracerFactory> previous_factory_; | |
| }; | |
| } // namespace credentio_tracing | |
| #endif // THIRD_PARTY_CREDENTIO_TRACING_SCOPED_TRACER_FACTORY_H_ |