How to send message from module to all Perspective sessions

I'm trying to communicate to all perspective sessions of a project when a process is finished in the module. Here is a simplified version of how I do it for a single session given its session ID.

public void sendPerspectiveSessionMessage(UUID sessionId, String messageType, PyDictionary payload) {
    var session = perspectiveContext.getSessionMonitor().findSession(sessionId);
    if (session.isEmpty()) {
        log.error("No active Perspective session with id {} found. Message of type {} not sent.", sessionId, messageType);
        return;
    }

    var message = new UserScopeMessageEvent(messageType, payload);
    session.get().queue().submit(() -> session.get().getEventManager().post(message));
}

Is there a way to obtain all sessions or session IDs? Or better yet, is there a way to communicate with all perspective sessions?

I see that PerspectiveSessionMonitor has a method getSessionInfos which returns a list of PerspectiveSessionInfo, but there is no accessor for ID. Are the IDs intentionally kept private?

Have the util function then call system.perspective.sendMessage if you need to adjust components or properties in the session scope.

Update: oop, I just saw the Module Development tag. Sorry if this wasn't what you were looking for!

I think you're at it, with PerspectiveSessionMonitor.

No, I don't think any such API exists (and anything we did have would be essentially what you're going to do - get all the sessions, broadcast a message to each one).

I don't think it's intentional or that these are meant to be 'secret' - it's just that none of our code has ever needed to expose that on the wrapped object you get from the overall list.

We use, internally, the PerspectiveSessionInfo.SimplifiedGsonEncoder to power the JSON encoding used in the routes.
You could, and I fully agree that this is hokey and unpleasant, get the full list, JSON encode it, and then pluck the id member from each encoded JSON object, e.g. by creating your own GSON adapter:

        gson = PerspectiveModule.createPerspectiveCompatibleGson(b -> {
            b.registerTypeHierarchyAdapter(
                PerspectiveSessionInfo.class,
                new PerspectiveSessionInfo.SimplifiedGsonEncoder());
        });

I'd probably just reflectively pull the id field off the object before I did that, though :person_shrugging:

3 Likes