Code cleanup. New implementation of long polling timeout. Done by server. Client...
authorLeonidas Poulopoulos <leopoul@noc.grnet.gr>
Sun, 11 Dec 2011 20:30:22 +0000 (22:30 +0200)
committerLeonidas Poulopoulos <leopoul@noc.grnet.gr>
Sun, 11 Dec 2011 20:30:22 +0000 (22:30 +0200)
flowspec/views.py
poller/views.py
templates/base.html
templates/poller.js
templates/user_routes.html

index a4d1ffd..c3f867c 100644 (file)
@@ -269,4 +269,5 @@ def user_logout(request):
     
 @never_cache
 def load_jscript(request, file):
-    return render_to_response('%s.js' % file, context_instance=RequestContext(request), mimetype="text/javascript")
+    long_polling_timeout = int(settings.POLL_SESSION_UPDATE)*1000 + 10000
+    return render_to_response('%s.js' % file, {'timeout': long_polling_timeout}, context_instance=RequestContext(request), mimetype="text/javascript")
index 3088fc0..00ca67c 100644 (file)
@@ -40,6 +40,7 @@ class Msgs(object):
     cache_size = 500
 
     def __init__(self):
+        logger.info("initializing")
         self.user = None
         self.user_cache = {}
         self.user_cursor = {}
@@ -63,7 +64,6 @@ class Msgs(object):
                 assert(self.new_message_user_event[user])
             except:
                 self.new_message_user_event[user] = Event()
-    #        self.new_message_user_event[user] = Event()
             try:
                 if self.user_cache[user]:
                     self.user_cursor[user] = self.user_cache[user][-1]['id']
@@ -88,7 +88,6 @@ class Msgs(object):
             self.user_cursor[user] = self.user_cache[user][-1]['id']
         else:
             self.user_cursor[user] = self.user_cache[user][-2]['id']
-#        self.cache.append(msg)
         if len(self.user_cache[user]) > self.cache_size:
             self.user_cache[user] = self.user_cache[user][-self.cache_size:]
         self.new_message_user_event[user].set()
@@ -99,7 +98,6 @@ class Msgs(object):
         if request.is_ajax():
             cursor = {}
             try:
-    #            user = request.user.username
                 user = request.user.get_profile().peer.domain_name
             except:
                 user = None
@@ -112,9 +110,7 @@ class Msgs(object):
             except:
                 self.user_cache[user] = []
             if not self.user_cache[user] or cursor[user] == self.user_cache[user][-1]['id']:
-                self.new_message_user_event[user].wait()
-    #            self.new_message_event.wait()
-    #        assert cursor[user] != self.user_cache[user][-1]['id'], cursor[user]
+                self.new_message_user_event[user].wait(settings.POLL_SESSION_UPDATE)
             try:
                 for index, m in enumerate(self.user_cache[user]):
                     if m['id'] == cursor[user]:
@@ -124,8 +120,6 @@ class Msgs(object):
                 if self.user_cache[user]:
                     self.user_cursor[user] = self.user_cache[user][-1]['id']
         return HttpResponseRedirect(reverse('group-routes'))
-    #            else:
-    #                request.session.pop('cursor', None)
 
     def monitor_polls(self, polls=None):
         b = beanstalkc.Connection()
@@ -144,7 +138,6 @@ class Msgs(object):
             p.spawn(self.monitor_polls)
             
 msgs = Msgs()
-
 main = msgs.main
 
 message_new = msgs.message_new
@@ -154,12 +147,3 @@ message_existing = msgs.message_existing
 poll = msgs.start_polling
 poll()
 
-
-
-
-
-
-
-
-
-
index af8c7df..a4374f4 100644 (file)
@@ -11,9 +11,6 @@
 <link rel="stylesheet" type="text/css" href="/static/css/smoothness/jquery-ui-1.8.13.custom.css">
 <script type="text/javascript" src="/static/js/jquery-ui-1.8.12.custom.min.js"></script>
 <script type="text/javascript" src="/static/js/jquery.tooltip.min.js"></script>
-{% if user.is_authenticated %}
-<script type="text/javascript" src="{% url load-js 'poller' %}"></script>
-{% endif %}
 <script type="text/javascript">
 
        function setlang(lang){
index bd75965..e5d0ede 100644 (file)
@@ -29,7 +29,7 @@ $(document).ready(function() {
     $("#message").select();
     {% if user.is_authenticated %}
     updater.start();
-    updater.keepalive();
+    updater.poll();
     
     {% endif %}
 });
@@ -57,11 +57,11 @@ function getCookie(name) {
 }
 
 jQuery.postJSON = function(url, args, callback) {
-    $.ajax({url: url, dataType: "text", type: "POST",
+    $.ajax({url: url, dataType: "json", type: "POST",
            success: function(response) {
-       if (callback) callback(eval("(" + response + ")"));
+       if (callback) callback(response);
     }, error: function(response) {
-       console.log("ERROR:", response)
+       console.log("ERROR:", response);
     }});
 };
 
@@ -92,42 +92,27 @@ jQuery.fn.enable = function(opt_enable) {
 var updater = {
     errorSleepTime: 500,
     cursor: null,
-    xhrlp: null,
-    keepalivetime:  120000,
-    keepalive: function (){
-       try {
-               updater.xhrlp.abort();
-       }
-       catch (e) {      
-       }
-       updater.poll();
-       if (updater.errorSleepTime == 500){
-               window.setTimeout(updater.keepalive, updater.keepalivetime);
-       }
-       else{
-               window.setTimeout(updater.keepalive, updater.keepalivetime+updater.errorSleepTime);
-       }
-       },
-    
     start: function() {
-               $.ajax({url: "{% url fetch-existing %}", type: "POST", dataType: "text",
+               $.ajax({url: "{% url fetch-existing %}", type: "POST", dataType: "json",
                success: updater.onFetchExisting,
                error: updater.onError});
         },
     
     poll: function() {
        {% if user.is_authenticated %}
-       if (updater.errorSleepTime > 60000){
-               window.setTimeout('location.reload()', 1000);
-               }
-       updater.xhrlp=$.ajax({url: "{% url fetch-updates %}", type: "POST", dataType: "text",
+       if (errorSleepTime > 128000){
+               window.setTimeout('location.reload()', 500);
+       }
+       timeout = {{timeout}};
+       $.ajax({url: "{% url fetch-updates %}", type: "POST", dataType: "json",
                success: updater.onSuccess,
+               timeout: timeout,
                error: updater.onError});
        {% endif %}
     },
     onSuccess: function(response) {
        try {
-           updater.newMessages(eval("(" + response + ")"));
+           updater.newMessages(response);
        } catch (e) {
            updater.onError();
            return;
@@ -138,27 +123,33 @@ var updater = {
 
     onFetchExisting: function(response) {
        try {
-           updater.existingMessages(eval("(" + response + ")"));
+           updater.existingMessages(response);
+
        } catch (e) {
-//         updater.onError();
+           updater.onError();
            return;
        }
         },
      
     onError: function(response, text) {
-               if (text != 'abort'){
-                               updater.errorSleepTime *= 2;
-                               console.log("Poll error; sleeping for", updater.errorSleepTime, "ms");
-                               window.setTimeout(updater.keepalive, updater.errorSleepTime);
+               if (text == 'timeout'){
+                       window.setTimeout('location.reload()', 3000);
                }
+               updater.errorSleepTime *= 2;
+                       console.log("Poll error; sleeping for", updater.errorSleepTime, "ms");
+                       window.setTimeout(updater.poll, updater.errorSleepTime);
+               
     },
 
     newMessages: function(response) {
        if (!response.messages) return;
+       if (response.messages.length == 0){
+               return true;
+       }
        updater.cursor = response.cursor;
        var messages = response.messages;
        updater.cursor = messages[messages.length - 1].id;
-//     console.log(messages.length, "new messages, cursor:", updater.cursor);
+       console.log(messages.length, "new messages, cursor:", updater.cursor);
        
        for (var i = 0; i < messages.length; i++) {
            updater.showMessage(messages[i]);
@@ -172,6 +163,9 @@ var updater = {
 
     existingMessages: function(response) {
        if (!response.messages) return;
+       if (response.messages.length == 0){
+               return true;
+       }
        updater.cursor = response.cursor;
        var messages = response.messages;
        updater.cursor = messages[messages.length - 1].id;
index cc8118c..f200f9c 100644 (file)
@@ -1,6 +1,9 @@
 {% extends "base.html" %}
 {% load i18n %}
 {% block extrahead %}
+{% if user.is_authenticated %}
+<script type="text/javascript" src="{% url load-js 'poller' %}"></script>
+{% endif %}
 <script type="text/javascript" src="/static/js/jquery.dataTables.js"></script>
 <script type="text/javascript">
        $(document).ready( function(){