atmosphere icon indicating copy to clipboard operation
atmosphere copied to clipboard

cacheLostMessage breaks broadcaster cache

Open xenster86 opened this issue 14 years ago • 18 comments

Version: 1.0.1 Configuration: long-polling, Apache Tomcat 7, Jersey

The issue is similar to the https://github.com/Atmosphere/atmosphere/issues/646 , however it has another root cause. When two(or more) messages are added to the same broadcaster with long-pooling transport within the same request, then the additional invocation to addCache is called by DefaultBroadcaster.cacheLostMessage (if AtmosphereResource can't deliver the second message to the some client within the same invocation). This call is not respected properly by the existing HeaderBroadcasterCache. Example: Assume 2 long-pooling connections r1,r2 stay at the server. The following method is called:

void sendIt() {
Broadcaster broadcater=...;
broadcaster.broadcast("e1");
broadcaster.broadcast("e2");
}

The invocation order of addToCache may have the following order (it depends on when executeAsyncWrite is being executed): addToCache:e1,r1 addToCache:e1,r2 addToCache:e2,r1 addToCache:e2,r2 addToCache:e2,r1 (this method is called by DefaultBroadcaster.cacheLostMessage if atmosphere detects that long-pooling connection r1 is already closed and the second message can not be pushed within the same request).

The problem is that broadcaster cache filters out the 'cacheLostMessage' invocation as duplicate, so this message is not stored in cache. Moreover, this message can't be stored in cache globally, because this message was lost only for the specific client's connection. Inserting it globally will cause a message duplicate for other clients. The solution is to use client's specific message queue. Here is my implementation of broadcaster cache which solves this problem:

/**
 *
 * @author Paul Khodchenkov
 */
public class EventCache implements BroadcasterCache {

    private final Map<String, ClientQueue> messages = new HashMap<>();

    private final Map<String, Long> activeClients = new HashMap<>();

    private ScheduledFuture scheduledFuture;

    private long clientIdleTime = TimeUnit.MINUTES.toMillis(2);//2 minutes

    private long invalidateCacheInterval = TimeUnit.MINUTES.toMillis(1);//1 minute

    private static class ClientQueue {

        private List<CacheMessage> queue = new ArrayList<>();

        private Set<String> ids = new HashSet<>();

        public List<CacheMessage> getQueue() {
            return queue;
        }

        public Set<String> getIds() {
            return ids;
        }
    }

    private static class CacheMessage {

        private final Object message;

        private final String id;

        private CacheMessage(String id, Object message) {
            this.id = id;
            this.message = message;
        }

        public Object getMessage() {
            return message;
        }

        public String getId() {
            return id;
        }
    }

    public void setInvalidateCacheInterval(long invalidateCacheInterval) {
        this.invalidateCacheInterval = invalidateCacheInterval;
    }

    public void setClientIdleTime(long clientIdleTime) {
        this.clientIdleTime = clientIdleTime;
    }


    @Override
    public void start() {
        TaskScheduler taskScheduler = AppContext.getBean("taskScheduler", TaskScheduler.class);
        scheduledFuture = taskScheduler.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                invalidateExpiredEntries();
            }
        }, invalidateCacheInterval);
    }

    protected void invalidateExpiredEntries() {
        long now = System.currentTimeMillis();
        synchronized (messages) {

            Set<String> inactiveClients = new HashSet<>();

            for (Map.Entry<String, Long> entry : activeClients.entrySet()) {
                if (now - entry.getValue() > clientIdleTime) {
                    inactiveClients.add(entry.getKey());
                }
            }

            for (String clientId : inactiveClients) {
                activeClients.remove(clientId);
                messages.remove(clientId);
            }

        }
    }

    @Override
    public void stop() {
        if (scheduledFuture != null) {
            scheduledFuture.cancel(false);
            scheduledFuture = null;
        }
    }

    @Override
    public void addToCache(String broadcasterId, AtmosphereResource r, Object e) {
        long now = System.currentTimeMillis();
        String messageId = //obtain message id
        CacheMessage cacheMessage = new CacheMessage(messageId, e);
        synchronized (messages) {
            if (r == null) {
                //no clients are connected right now, caching message for all active clients
                for (Map.Entry<String, Long> entry : activeClients.entrySet()) {
                    addMessageIfNotExists(entry.getKey(), cacheMessage);
                }
            } else {
                String clientId = r.uuid();
                activeClients.put(clientId, now);
                if (isAtmosphereResourceValid(r)) {//todo better to have cacheLost flag
                    /**
                     * This line is called for each AtmosphereResource (note that
                     * broadcaster.getAtmosphereResources() may not return the current AtmosphereResource because
                     * the resource may be destroyed by DefaultBroadcaster.executeAsyncWrite or JerseyBroadcasterUtil
                     * concurrently, that is why we need to check duplicates),
                     *
                     * Cache the message only once for the clients
                     * which are not currently connected to the server
                     */
                    Broadcaster broadcaster = getBroadCaster(broadcasterId);
                    List<AtmosphereResource> resources = new ArrayList<>(broadcaster.getAtmosphereResources());
                    Set<String> disconnectedClients = getDisconnectedClients(resources);
                    for (String disconnectedId : disconnectedClients) {
                        addMessageIfNotExists(disconnectedId, cacheMessage);
                    }
                } else {
                    /**
                     * Cache lost message, caching only for specific client.
                     * Preventing duplicate inserts because this method can be called
                     * concurrently from DefaultBroadcaster.executeAsyncWrite or JerseyBroadcasterUtil
                     * when calling cacheLostMessage
                     */
                    addMessageIfNotExists(clientId, cacheMessage);
                }
            }
        }
    }

    private boolean isAtmosphereResourceValid(AtmosphereResource r) {
        return !r.isResumed()
                && !r.isCancelled()
                && AtmosphereResourceImpl.class.cast(r).isInScope();
    }

    private Set<String> getDisconnectedClients(List<AtmosphereResource> resources) {
        Set<String> ids = new HashSet<>(activeClients.keySet());
        for (AtmosphereResource resource : resources) {
            Assert.notNull(resource.uuid());
            ids.remove(resource.uuid());
        }
        return ids;
    }

    private Broadcaster getBroadCaster(String broadcasterId) {
        BroadcasterFactory factory = BroadcasterFactory.getDefault();
        Broadcaster broadcaster = factory.lookup(broadcasterId, false);
        Assert.notNull(broadcaster);
        return broadcaster;
    }

    private void addMessageIfNotExists(String clientId, CacheMessage message) {
        if (!hasMessage(clientId, message.getId())) {
            addMessage(clientId, message);
        }
    }

    private void addMessage(String clientId, CacheMessage message) {
        ClientQueue clientQueue = messages.get(clientId);
        if (clientQueue == null) {
            clientQueue = new ClientQueue();
            messages.put(clientId, clientQueue);
        }
        clientQueue.getQueue().add(message);
        clientQueue.getIds().add(message.getId());
    }

    private boolean hasMessage(String clientId, String messageId) {
        ClientQueue clientQueue = messages.get(clientId);
        return clientQueue != null && clientQueue.getIds().contains(messageId);
    }

    @Override
    public List<Object> retrieveFromCache(String broadcasterId, AtmosphereResource r) {
        Assert.notNull(r, "AtmosphereResource can't be null");
        String clientId = r.uuid();
        long now = System.currentTimeMillis();

        List<Object> result = new ArrayList<>();

        ClientQueue clientQueue;
        synchronized (messages) {
            activeClients.put(clientId, now);
            clientQueue = messages.remove(clientId);
        }
        List<CacheMessage> clientMessages;
        if (clientQueue == null) {
            clientMessages = Collections.emptyList();
        } else {
            clientMessages = clientQueue.getQueue();
        }

        for (CacheMessage cacheMessage : clientMessages) {
            result.add(cacheMessage.getMessage());
        }
        return result;
    }

}

It would be fine to pass cacheLostMessage flag to addToCache in order to not duplicate the code for 'isAtmosphereResourceValid'. Moreover, it would be better to wrap cache arguments into single composite parameter, in order to simplify handling the case when addToCache is called multiply times for the same message and keep method signature simpler:

class CacheRequest {
List<AtmosphereResource> resources;
Object message;
boolean cacheLost;
String broadcasterId;
}

void addToCache(CacheRequest  request);

The second problem is that atmosphere calls addToCache method (except the case when cacheLostMessage is called) for all ACTIVE connections, however we need to cache message for the clients which are not currently connected to the server (in the middle of reconnecting). To solve this problem i use 'activeClients' map which is updated on addToCache and retrieveFromCache. However, this will work properly only for long-pooling connections.

xenster86 avatar Sep 30 '12 14:09 xenster86

@werdex Can you do a pull request with your code change? I don't care about the Spring usage (I will remove it) but at least will be much more simpler for me to make it work based on your observation. Thanks!

jfarcand avatar Oct 04 '12 20:10 jfarcand

Hi jfarcand, Actually it is to early to do a pull request, because we need to think about proper way of detecting clients which are currently in the middle of reconnecting :). Currently, addToCache is called for each active connection on the server when message is pushed or when cacheLost happens for the specific connection. I suppose it would be better if addToCache is called when the message should be really cached for those clients which are currently not connected to the server (or when cacheLost happens). Do you have any better way of tracking such disconnected clients? Can atmosphere maintain something similar to my 'activeClients' map internally using client id and calculate which clients are currently not connected to the server and call addToCache for each disconnected client?

xenster86 avatar Oct 05 '12 10:10 xenster86

Salut, that won't scale if we track activeClient (AsynchronousProcessor has some support), but I think we could write an AtmosphereInterceptor to track user. Also the current implementation seems to suffer some issues (I did extensive testing this morning with basic test)...let me dig into that first and then I will fix the corner case/edge case.

jfarcand avatar Oct 05 '12 12:10 jfarcand

Hi, What is the problem with scaling when detecting activeClients per broadcaster :) ? We just need to keep some client id in map and last activity time (when client connects or when message is being sent to that client ). Map entries should be invalidated when client is idle for too long time...

xenster86 avatar Oct 05 '12 12:10 xenster86

Well, for my deployment to WSJ.com I can tell you keeping state of the connection cost a lot and handling disconnection etc. makes the code complex. But I agree we need to have something anyway. Looking this morning. Would it be easier to create a branch and works on it together for you?

jfarcand avatar Oct 05 '12 13:10 jfarcand

Hi, Yes, it would be nice if you create a branch.

xenster86 avatar Oct 05 '12 13:10 xenster86

I'm getting bitten by this as well, it seems. :-) What's the status on this?

dxmann73 avatar Nov 29 '12 10:11 dxmann73

@wedex: Any chance to do a pull request so I can start the new implementation based on your experience? @dxmann73 I'm quite swaped at work, so right now I will need "community" help to deliver the fix.

jfarcand avatar Dec 03 '12 14:12 jfarcand

Hi jfarcand, I am currently using only long-pooling transport and my implementation of the cache listed above seems to work fine (it will not properly with websockets). But i am afraid that it is just the workaround for more generic problem: we need to store lost messages in the client's specific queue (as, for example, GWTEventService project does which pushes the messages to all active clients queues and then each client connections retrieve this message separately when connection arrives to server) because message lost happens with specific client connection. So the proper fix (for all transports) will require a lot amount of work... For long-pooling connections you may use the implementation of the cache listed above as workaround for now...

xenster86 avatar Dec 03 '12 15:12 xenster86

Back to this issue...@werdex , have you implemented your proposal already :-) That would be my lucky day :-)

jfarcand avatar Jan 14 '13 22:01 jfarcand

Ported the class, make it working with WebSocket. Doing more testing. @werdex, please review :-) :-)

jfarcand avatar Jan 23 '13 10:01 jfarcand

Hi jfarcand, Can we do something with 'if (isAtmosphereResourceValid(r)' because i have copy pasted it from AtmosphereResourceImpl in order to detect if cacheLostMessage method was called :) I think it would be fine if when cacheLostMessage is called by AtmosphereResourceImpl or other class then some flag is passed to the cache so we can avoid double check in 'isAtmosphereResourceValid'.

xenster86 avatar Jan 23 '13 15:01 xenster86

@werdex Agree. I will look at it, right now I'm writing tests :-)

jfarcand avatar Jan 24 '13 14:01 jfarcand

Hi, i think it's better to wrap all params in one composite class CacheRequest(for example), in order to prevent BroadcasterCache signtature change when new parameters are passed to addToCache method.

xenster86 avatar Jan 24 '13 15:01 xenster86

Indeed. Pull request?

jfarcand avatar Jan 24 '13 15:01 jfarcand

Hi All,

I have a single page application. In it, only one page (dashboard), contains a widget which can receive server push. However when other pages are loaded, then they are not eligible for receiving the messages. Now can I track this with the Interceptor? Including no url change but separete page load done by a typical ajax call.

Thanks for the help in advance..

Regards, Amit

amitpa-nrift avatar Oct 21 '13 14:10 amitpa-nrift

@amitpa-nrift Issue tracker is not for question. Please use the mailing list.

jfarcand avatar Oct 21 '13 14:10 jfarcand

Thanks for the reply I will post in the mailing list

On Mon, Oct 21, 2013 at 7:42 PM, Jeanfrancois Arcand < [email protected]> wrote:

@amitpa-nrift https://github.com/amitpa-nrift Issue tracker is not for question. Please use the mailing list.

— Reply to this email directly or view it on GitHubhttps://github.com/Atmosphere/atmosphere/issues/658#issuecomment-26720108 .

amitpa-nrift avatar Oct 21 '13 14:10 amitpa-nrift