| // 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 "async/cancellation_token.h" |
| |
| #include <cstdint> |
| #include <utility> |
| #include <vector> |
| |
| #include "absl/functional/any_invocable.h" |
| #include "absl/synchronization/mutex.h" |
| |
| namespace credentio { |
| |
| void CancellationState::Cancel() { |
| std::vector<absl::AnyInvocable<void()>> to_run; |
| |
| { |
| absl::MutexLock lock(mutex_); |
| if (cancelled_) return; |
| cancelled_ = true; |
| |
| to_run.reserve(callbacks_.size()); |
| for (auto& pair : callbacks_) { |
| to_run.push_back(std::move(pair.second)); |
| } |
| callbacks_.clear(); |
| } |
| |
| // Execute callbacks without holding the lock to avoid deadlocks. |
| for (auto& cb : to_run) { |
| if (cb) { |
| cb(); |
| } |
| } |
| } |
| |
| uint64_t CancellationState::RegisterCallback(absl::AnyInvocable<void()> cb) { |
| { |
| absl::MutexLock lock(mutex_); |
| if (!cancelled_) { |
| uint64_t id = next_id_++; |
| callbacks_[id] = std::move(cb); |
| return id; |
| } |
| } |
| |
| // If already cancelled, execute immediately and return 0 (no unregister |
| // needed). |
| if (cb) { |
| cb(); |
| } |
| return 0; |
| } |
| |
| void CancellationState::DeregisterCallback(uint64_t id) { |
| absl::MutexLock lock(mutex_); |
| callbacks_.erase(id); |
| } |
| |
| } // namespace credentio |