/* Copyright 2025 The OpenXLA Authors.

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

    http://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 XLA_PJRT_SCOPED_ASYNC_TRACKING_EVENT_H_
#define XLA_PJRT_SCOPED_ASYNC_TRACKING_EVENT_H_

#include "xla/future.h"
#include "xla/tsl/concurrency/async_value.h"
#include "xla/tsl/concurrency/ref_count.h"

namespace xla {

// An RAII event that a caller can use to tell the PjRtClient about asynchronous
// actions outside PjRt.
//
// A ScopedAsyncTrackingEvent can be generated by the caller by calling a method
// on PjRtDevice, and the creation of a ScopedAsyncTrackingEvent tells the
// PjRtClient that the client is creating some outstanding asynchronous work
// that depends on activities happening on the PjRtDevice.
//
// The caller can indicate that a ScopedAsyncTrackingEvent event cannot complete
// until after some Future becomes ready, by calling
// event.AddDependency(future).
//
// The caller indicates that the work tracked by the ScopedAsyncTrackingEvent
// has completed by letting the event go out of scope.
//
// ScopedAsyncTrackingEvent is used by some PjRtClient implementations to
// monitor system-wide dependencies.
class ScopedAsyncTrackingEvent {
 public:
  virtual ~ScopedAsyncTrackingEvent() = default;

  template <typename T>
  void AddDependency(const Future<T>& future) {
    AddDependency(FormRef(future.async_value()));
  }

 private:
  // Indicates that the ScopedAsyncTrackingEvent won't complete until dependency
  // becomes available.
  virtual void AddDependency(tsl::RCReference<tsl::AsyncValue> dependency) = 0;
};

}  // namespace xla

#endif  // XLA_PJRT_SCOPED_ASYNC_TRACKING_EVENT_H_
