<commit_before>var io = require('socket.io-client');
var totalMessageCount = 0;

module.exports = function(options) {
  var url    = options.url;

  var start = function(id, done) {
    var client = io(url, {transports: ['websocket']});
    var publish    = function(event, data) { client.emit(event, data); };

    var subscribe  = function(event, cb)   {
      client.on(event, function(data) {
        totalMessageCount++;
        cb(data);
      });
    };

    var messageCounts   = {};
    var claimedStudents = 0;
    var lastStats       = null;

    var connect = function() {
      publish('presence:teacher:connect', {
        userId: id,
        role:   'teacher'
      });
    };

    var onStatusUpdate = function(data) {
      lastStats = data;

      if(data.students.waiting == 0 && data.students.total == 0) {
        console.log('teachers received ' + totalMessageCount + ' messages.');
        done();
      }
    };

    var tryToClaimStudent = function() {
      if(claimedStudents < 5 && (lastStats == null || lastStats.students.waiting > 0)) {
        publish('presence:claim_student', { teacherId: id })
      }
    };

    var messageCount = function(chatId) {
      if(messageCounts[chatId] === undefined) {
        messageCounts[chatId] = 0;
      }

      return messageCounts[chatId];
    }

    var sendNextMessage = function(chatId, channel) {
      var count = messageCount(chatId) + 1;
      messageCounts[chatId] = count;

      publish(channel, {
        chatId:  chatId,
        message: 'Message from teacher: ' + count
      });
    };

    var handleNewChat = function(chat) {
      var sendChannel      = chat.sendChannel;
      var receiveChannel   = chat.receiveChannel;
      var terminateChannel = chat.terminateChannel;
      var terminatedChannel = chat.terminatedChannel;
      var joinedChannel    = chat.joinedChannel;
      var readyChannel     = chat.readyChannel;

      claimedStudents++;
      console.log('Teacher now has ' + claimedStudents + ' students.');

      subscribe(receiveChannel, function(data) {
        //console.log('Teacher got chat message:', data);

        if(messageCount(chat.id) < options.messageCount) {
          sendNextMessage(chat.id, sendChannel);
        }
        else {
          publish(terminateChannel, {
            chatId:  chat.id,
            message: 'teacher is ending the chat.'
          });
        }
      });

      //wait for student to join
      subscribe(readyChannel, function(data) {
        // kick off the whole shebang
        sendNextMessage(chat.id, sendChannel);
      });

      subscribe(terminatedChannel, function(data) {
        claimedStudents--;
        console.log('Teacher now has ' + claimedStudents + ' students.');
        tryToClaimStudent();
      })

      publish(joinedChannel, { chatId: chat.id, userId: id });
    };

    client.on('connect_error', function(data) {
      console.log('teacher connection error: ', data);
    });

    subscribe('presence:status', onStatusUpdate);
    subscribe('presence:new_chat:teacher:' + id, handleNewChat);
    connect();
    setInterval(tryToClaimStudent, 10);
  };

  return {
    start: start
  }
};<commit_msg>Don't ping the server too hard or we'll stack up requests.<commit_after>var io = require('socket.io-client');
var totalMessageCount = 0;

module.exports = function(options) {
  var url    = options.url;

  var start = function(id, done) {
    var client = io(url, {transports: ['websocket']});
    var publish    = function(event, data) { client.emit(event, data); };

    var subscribe  = function(event, cb)   {
      client.on(event, function(data) {
        totalMessageCount++;
        cb(data);
      });
    };

    var messageCounts   = {};
    var claimedStudents = 0;
    var lastStats       = null;

    var connect = function() {
      publish('presence:teacher:connect', {
        userId: id,
        role:   'teacher'
      });
    };

    var onStatusUpdate = function(data) {
      lastStats = data;

      if(data.students.waiting == 0 && data.students.total == 0) {
        console.log('teachers received ' + totalMessageCount + ' messages.');
        done();
      }
    };

    var tryToClaimStudent = function() {
      if(claimedStudents < 5 && (lastStats == null || lastStats.students.waiting > 0)) {
        //console.log('teacher ' + id + ' is asking for another kid. They have ' + claimedStudents + ' kids.')
        publish('presence:claim_student', { teacherId: id })
      }
    };

    var messageCount = function(chatId) {
      if(messageCounts[chatId] === undefined) {
        messageCounts[chatId] = 0;
      }

      return messageCounts[chatId];
    }

    var sendNextMessage = function(chatId, channel) {
      var count = messageCount(chatId) + 1;
      messageCounts[chatId] = count;

      publish(channel, {
        chatId:  chatId,
        message: 'Message from teacher: ' + count
      });
    };

    var handleNewChat = function(chat) {
      var sendChannel      = chat.sendChannel;
      var receiveChannel   = chat.receiveChannel;
      var terminateChannel = chat.terminateChannel;
      var terminatedChannel = chat.terminatedChannel;
      var joinedChannel    = chat.joinedChannel;
      var readyChannel     = chat.readyChannel;
      var hasTerminated    = false;

      claimedStudents++;
      console.log('Teacher now has ' + claimedStudents + ' students.');

      subscribe(receiveChannel, function(data) {
        //console.log('Teacher got chat message:', data);

        if(messageCount(chat.id) < options.messageCount) {
          sendNextMessage(chat.id, sendChannel);
        }
        else if(!hasTerminated) {
          hasTerminated = true;
          publish(terminateChannel, {
            chatId:  chat.id,
            message: 'teacher is ending the chat.'
          });
        }
      });

      //wait for student to join
      subscribe(readyChannel, function(data) {
        // kick off the whole shebang
        sendNextMessage(chat.id, sendChannel);
      });

      subscribe(terminatedChannel, function(data) {
        claimedStudents--;
        console.log('Teacher now has ' + claimedStudents + ' students.');
        tryToClaimStudent();
      })

      publish(joinedChannel, { chatId: chat.id, userId: id });
    };

    client.on('connect_error', function(data) {
      console.log('teacher connection error: ', data);
    });

    subscribe('presence:status', onStatusUpdate);
    subscribe('presence:new_chat:teacher:' + id, handleNewChat);
    connect();
    setInterval(tryToClaimStudent, 500);
  };

  return {
    start: start
  }
};
{'fraction_non_alphanumeric': 0.12632375189107414, 'fraction_numerical': 0.003177004538577912, 'mean_word_length': 2.4307213284898808, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4398015', 'n_tokens_mistral': 1981, 'n_tokens_neox': 1883, 'n_words': 419}