Obtain actor-handle from within an actor to self

From within a ray actor I would like to obtain a handle to my own actor and pass it via remote calls. This is necessary for implementing a flow that follows the “observer-pattern”. In such flow, actor “C” invokes a remote call to “P” of the form P_handle.subscribe.remote(C_handle) to register itself as an “observer” (consumer).

How can actor “C” obtain C_handle in such case?

Thanks,
Elad

Hey @eladgm - Thanks for the question.

AFAIK, there’s no current API for doing so.

However, when you create the actor, you will get the actor handle, and you should be able to pass the handle as an argument to the actor method.

Assuming you have an actor method that calls

@ray.remote
class Actor:
    def subscribe(self, C_ref, P_ref):
        P_ref.subscribe.remote(C_ref)

And you pass the actor ref at the caller side:

c = Actor.remote()
p = P.remote()
c.subscribe.remote(c, p)

Will this work for your usecase?

You could actually do so by (in your actor method)


ctx = ray.get_runtime_context()
actor_handle = ctx.current_actor()

https://docs.ray.io/en/latest/ray-core/api/doc/ray.runtime_context.RuntimeContext.html?highlight=current_actor
and ray.runtime_context.get_runtime_context — Ray 2.3.1

1 Like

Thanks! Great. That is exactly what I was looking for. The following code works for me for checking if the current execution is within an actor, and if so obtain a handle to it:

def get_handle_to_current_actor() -> Optional[ray.actor.ActorHandle]:
    """
    Obtain an handle to current actor if executed within one.
    """
    ctx = ray.get_runtime_context()
    if not ctx.worker.mode:
        return None  # not inside of an actor
    return ctx.current_actor
1 Like