Handles the heartbeat response from the worker handler.
354855
private function handleHeartbeatResponse()
    {
        $state = $this->worker->getState();
        if (Worker::BUSY == $state) {
            /**
             * We should only reply in the following cases:
             * - A heartbeat is about to expire.
             * - We have a result.
             */
            return;
        }

        if (Worker::RESULT_AVAILABLE == $state) {
            // A result is available send it to the worker handler.
            $this->handleResult();

            return;
        }

        if (in_array($state, array(Worker::READY, Worker::RESULT, Worker::REGISTER))) {
            // Update the state to ready and forget about the last job.
            $this->worker->cleanup();

            // Request a new job
            $this->sendToWorkerHandler(new GetJobRequest());

            return;
        }

        if (Worker::SHUTDOWN != $state) {
            // The worker did not request a shutdown, however all other states should be handled at this point.
            $this->getLogger()->error('Invalid worker state: '.$this->worker->getState().'.');
        }

        // Worker is completely shutdown, because there is no open connection to the worker handler.
        $this->worker->setState(Worker::INVALID);
    }
114106
protected function handleHeartbeat($data)
    {
        $this->logger->debug('received heartbeat', ['seq' => $data->d]);

        $payload = [
            'op' => Op::OP_HEARTBEAT,
            'd'  => $data->d,
        ];

        $this->send($payload);
    }
752540
function responseHandler(err, res) {
            //console.log('resp', err, res.status);
            // Handle connection HTTPS errors.
            if (err){
                d.reject(err);
            }else {
                var answer = {
                    code: res.status,
                    headers: res.headers,
                    data: res.body
                };

                // Check if response is IDOL API error or not
                if (res.status < 200 || res.status >= 300) {
                    // YES it is error.
                    // Resolve the promise with the error.
                    d.reject(answer);
                } else {
                    // NO it is not error.
                    // Queue the job for polling if it is async job.
                    if (options.type == 'async' && Boolean(self.options.autoResult)) {
                        self
                            .jobResult(res.body.jobID)
                            .done(
                                _.partial(self.emit, 'job result'),
                                _.partial(self.emit, 'job result error')
                        );
                    }
                    // Resolve the promise with the result.
                    d.resolve(answer);
                }
            }
        }
591315
def heartbeat(time)
      RRRSpec.redis.setex(RRRSpec.make_key(key, 'heartbeat'), time, "alive")
      RRRSpec.redis.sadd(RRRSpec.make_key('rrrspec', 'worker'), key)
    end
621316
def on_heartbeat(self, message):
        

        logger.info("Got a heartbeat")
        logger.info("Heartbeat message: {}".format(message))
        self.heartbeat_thread.update_sequence(message['d'])
        return
599720
def _heartbeat_view(self):
        
        details = {}
        statuses = {}
        level = 0

        for name, check in self.checks.items():
            detail = self._heartbeat_check_detail(check)
            statuses[name] = detail['status']
            level = max(level, detail['level'])
            if detail['level'] > 0:
                details[name] = detail

        payload = {
            'status': checks.level_to_text(level),
            'checks': statuses,
            'details': details,
        }

        def render(status_code):
            return make_response(jsonify(payload), status_code)

        if level < checks.WARNING:
            status_code = 200
            heartbeat_passed.send(self, level=level)
            return render(status_code)
        else:
            status_code = 500
            heartbeat_failed.send(self, level=level)
            raise HeartbeatFailure(response=render(status_code))
734429
function responseHandler (res, next) {
  return function (err, message) {
    if (err || !message) {
      next(err);
    } else {
      res.send(message);
    }
  }
}
443625
def handle_data(self, ts, msg):
        
        try:
            chan_id, *data = msg
        except ValueError as e:
            # Too many or too few values
            raise FaultyPayloadError("handle_data(): %s - %s" % (msg, e))
        self._heartbeats[chan_id] = ts
        if data[0] == 'hb':
            self._handle_hearbeat(ts, chan_id)
            return
        try:
            self.channels[chan_id](ts, chan_id, data)
        except KeyError:
            raise NotRegisteredError("handle_data: %s not registered - "
                                     "Payload: %s" % (chan_id, msg))
119470
def _get_monitoring_heartbeat(self):
        
        target = self.uri + '/monitoring/heartbeat'
        response = self.session.get(target)
        return response
771384
def heartbeat(self):
        
        while not self.ws.closed:
            gevent.sleep(HEARTBEAT_DELAY)
            gevent.spawn(self.send, "ping")
1258715
def handle(self):
        """"""
        rv = None
        try:
            rv = BaseHTTPRequestHandler.handle(self)
        except (_ConnectionError, socket.timeout) as e:
            self.connection_dropped(e)
        except Exception as e:
            if self.server.ssl_context is None or not is_ssl_error(e):
                raise
        if self.server.shutdown_signal:
            self.initiate_shutdown()
        return rv
1357534
def heartbeat(self):
        
        if self._rpc is not None and self._rpc.is_active:
            self._rpc.send(types.StreamingPullRequest())
622496
private byte[] handleHeartbeat(Address address, byte[] message) {
    GossipMember remoteMember = SERIALIZER.decode(message);
    LOGGER.trace("{} - Received heartbeat: {}", localMember.id(), remoteMember);
    failureDetectors.computeIfAbsent(remoteMember.id(), n -> new PhiAccrualFailureDetector()).report();
    updateMember(remoteMember, true);

    // Return only reachable members to avoid populating removed members on remote nodes from unreachable members.
    return SERIALIZER.encode(Lists.newArrayList(members.values()
        .stream()
        .filter(member -> member.isReachable())
        .collect(Collectors.toList())));
  }
1221636
def Heartbeat(self):
    """"""
    service_key = _GetServiceKey()
    try:
      winreg.SetValueEx(service_key, "Nanny.heartbeat", 0, winreg.REG_DWORD,
                        int(time.time()))
    except OSError as e:
      logging.debug("Failed to heartbeat nanny at %s: %s", service_key, e)
1085040
protected void handleAppendResponse(MemberState member, AppendRequest request, AppendResponse response) {
    // Trigger commit futures if necessary.
    updateHeartbeatTime(member, null);

    super.handleAppendResponse(member, request, response);
  }
925769
function handleWSMessage(data, flags) {
	var message = decompressWSMessage(data, flags);
	var _data = message.d;
	var client = this, user, server, member, old,
	userID, serverID, channelID, currentVCID,
	mute, deaf, self_mute, self_deaf;

	switch (message.op) {
		case 0:
			//Event dispatched - update our sequence number
			client.internals.sequence = message.s;
			break;
		case 1:
			//Heartbeat requested by Discord - send one immediately
			send(client._ws, Payloads.HEARTBEAT(client));
			break;
		case 7:
			//Reconnect requested by discord
			clearTimeout(client.internals.heartbeat);
			client._ws.close(1000, 'Reconnect requested by Discord');
			break;
		case 9:
			//Disconnect after an Invalid Session
			//Disconnect the client if the client has received an invalid session id
			if(!message.d) {
				delete(client.internals.sequence);
				delete(client.internals.sessionID);
				//Send new identify after 1-5 seconds, chosen randomly (per Gateway docs)
				setTimeout(function() {
					identifyOrResume(client);
				}, Math.random()*4000+1000);
			} else identifyOrResume(client);
			
			
			break;
		case 10:
			//Start keep-alive interval
			//Disconnect the client if no ping has been received
			//Since v3 you send the IDENTIFY/RESUME payload here.
			identifyOrResume(client);
			if(!client.presence) client.presence = { status: "online", since: Date.now() };
			client.connected = true;

			client._mainKeepAlive = setInterval(function() {
				client.internals.heartbeat = setTimeout(function() {
					client._ws && client._ws.close(1001, "No heartbeat received");
				}, _data.heartbeat_interval);
				client.internals._lastHB = Date.now();
				send(client._ws, Payloads.HEARTBEAT(client));
			}, _data.heartbeat_interval);
			break;
		case 11:
			clearTimeout(client.internals.heartbeat);
			client.internals._pings.unshift(Date.now() - client.internals._lastHB);
			client.internals._pings = client.internals._pings.slice(0, 10);
			break;
	}

	//Events
	client.emit('any', message);
	//TODO: Remove in v3
	client.emit('debug', message);
	switch (message.t) {
		case "READY":
			copyKeys(_data.user, client);
			client.internals.sessionID = _data.session_id;

			getServerInfo(client, _data.guilds);
			getDirectMessages(client, _data.private_channels);

			if (client.bot) client.getOauthInfo(function(err, res) {
				if (err) return console.log(err);
				client.internals.oauth = res;
				client.inviteURL = "https://discordapp.com/oauth2/authorize?client_id=" + res.id + "&scope=bot";
			});
			if (!client.bot) client.getAccountSettings(function(err, res) {
				if (err) return console.log(err);
				client.internals.settings = res;
			});

			return (function() {
				if (client._ready) return;
				var ready = [false];
				setTimeout(function() { ready[0] = true; }, 3500);
				checkForAllServers(client, ready, message);
			})();
		case "MESSAGE_CREATE":
			client.emit('message', _data.author.username, _data.author.id, _data.channel_id, _data.content, message);
			emit(client, message, _data.author.username, _data.author.id, _data.channel_id, _data.content);
			return cacheMessage(client._messageCache, client._messageCacheLimit, _data.channel_id, _data);
		case "MESSAGE_UPDATE":
			try {
				emit(client, message, client._messageCache[_data.channel_id][_data.id], _data);
			} catch (e) { emit(client, message, undefined, _data); }
			return cacheMessage(client._messageCache, client._messageCacheLimit, _data.channel_id, _data);
		case "PRESENCE_UPDATE":
			if (!_data.guild_id) break;

			serverID = _data.guild_id;
			userID = _data.user.id;

			if (!client.users[userID]) client.users[userID] = new User(_data.user);

			user = client.users[userID];
			member = client.servers[serverID].members[userID] || {};

			copyKeys(_data.user, user);
			user.game = _data.game;

			copyKeys(_data, member, ['user', 'guild_id', 'game']);
			client.emit('presence', user.username, user.id, member.status, user.game, message);
			break;
		case "USER_UPDATE":
			copyKeys(_data, client);
			break;
		case "USER_SETTINGS_UPDATE":
			copyKeys(_data, client.internals);
			break;
		case "GUILD_CREATE":
			/*The lib will attempt to create the server using the response from the
			REST API, if the user using the lib creates the server. There are missing keys, however.
			So we still need this GUILD_CREATE event to fill in the blanks.
			If It's not our created server, then there will be no server with that ID in the cache,
			So go ahead and create one.*/
			client.servers[_data.id] = new Server(client, _data);
			return emit(client, message, client.servers[_data.id]);
		case "GUILD_UPDATE":
			old = copy(client.servers[_data.id]);
			Server.update(client, _data);
			return emit(client, message, old, client.servers[_data.id]);
		case "GUILD_DELETE":
			emit(client, message, client.servers[_data.id]);
			return delete(client.servers[_data.id]);
		case "GUILD_MEMBER_ADD":
			client.users[_data.user.id] = new User(_data.user);
			client.servers[_data.guild_id].members[_data.user.id] = new Member(client, client.servers[_data.guild_id], _data);
			client.servers[_data.guild_id].member_count += 1;
			return emit(client, message, client.servers[_data.guild_id].members[_data.user.id]);
		case "GUILD_MEMBER_UPDATE":
			old = copy(client.servers[_data.guild_id].members[_data.user.id]);
			Member.update(client, client.servers[_data.guild_id], _data);
			return emit(client, message, old, client.servers[_data.guild_id].members[_data.user.id]);
		case "GUILD_MEMBER_REMOVE":
			if (_data.user && _data.user.id === client.id) return;
			client.servers[_data.guild_id].member_count -= 1;
			emit(client, message, client.servers[_data.guild_id].members[_data.user.id]);
			return delete(client.servers[_data.guild_id].members[_data.user.id]);
		case "GUILD_ROLE_CREATE":
			client.servers[_data.guild_id].roles[_data.role.id] = new Role(_data.role);
			return emit(client, message, client.servers[_data.guild_id].roles[_data.role.id]);
		case "GUILD_ROLE_UPDATE":
			server = client.servers[_data.guild_id];
			old = copy(server.roles[_data.role.id]);
			Role.update(server, _data);
			Object.keys(server.members).forEach(function(memberID) {
				var member = server.members[memberID];
				if ( member.roles.indexOf(_data.role.id) < 0 ) return;
				member.color = colorFromRole(server, member);
			});
			return emit(client, message, old, server.roles[_data.role.id]);
		case "GUILD_ROLE_DELETE":
			if (client.servers[_data.guild_id]){
				emit(client, message, client.servers[_data.guild_id].roles[_data.role_id]);
				return delete(client.servers[_data.guild_id].roles[_data.role_id]);
			}
			break;
		case "CHANNEL_CREATE":
			channelID = _data.id;

			if (_data.type == 1) {
				if (client.directMessages[channelID]) return;
				client.directMessages[channelID] = new DMChannel(client._uIDToDM, _data);
				return emit(client, message, client.directMessages[channelID]);
			}

			if (client.channels[channelID]) return;
			client.channels[channelID] = new Channel(client, client.servers[_data.guild_id], _data);
			return emit(client, message, client.channels[channelID]);
		case "CHANNEL_UPDATE":
			old = copy(client.channels[_data.id]);
			Channel.update(client, _data);
			return emit(client, message, old, client.channels[_data.id]);
		case "CHANNEL_DELETE":
			if (_data.type == 1) {
				emit(client, message, client.directMessages[_data.id]);
				delete(client.directMessages[_data.id]);
				return delete(client._uIDToDM[_data.recipients[0].id]);
			}
			Object.keys(client.servers[_data.guild_id].members).forEach(function(m) {
				if (client.servers[_data.guild_id].members[m].voice_channel_id == _data.id) {
					client.servers[_data.guild_id].members[m].voice_channel_id = null;
				}
			});
			emit(client, message, client.servers[_data.guild_id].channels[_data.id]);
			delete(client.servers[_data.guild_id].channels[_data.id]);
			return delete(client.channels[_data.id]);
		case "GUILD_EMOJIS_UPDATE":
			old = copy(client.servers[_data.guild_id].emojis);
			Emoji.update(client.servers[_data.guild_id], _data.emojis);
			return emit(client, message, old, client.servers[_data.guild_id].emojis);
		case "VOICE_STATE_UPDATE":
			serverID = _data.guild_id;
			channelID = _data.channel_id;
			userID = _data.user_id;
			server = client.servers[serverID];
			mute = !!_data.mute;
			self_mute = !!_data.self_mute;
			deaf = !!_data.deaf;
			self_deaf = !!_data.self_deaf;

			try {
				currentVCID = server.members[userID].voice_channel_id;
				if (currentVCID) delete( server.channels[currentVCID].members[userID] );
				if (channelID) server.channels[channelID].members[userID] = _data;
				server.members[userID].mute = (mute || self_mute);
				server.members[userID].deaf = (deaf || self_deaf);
				server.members[userID].voice_channel_id = channelID;
			} catch(e) {}

			if (userID === client.id) {
				server.self_mute = self_mute;
				server.self_deaf = self_deaf;
				if (channelID === null) {
					if (server.voiceSession) leaveVoiceChannel(client, server.voiceSession.channelID);
					server.voiceSession = null;
				} else {
					if (!server.voiceSession) {
						server.voiceSession = getVoiceSession(client, channelID, server);
					}
					if (channelID !== server.voiceSession.channelID) {
						delete( client._vChannels[server.voiceSession.channelID] );
						getVoiceSession(client, channelID, server).channelID = channelID;
					}

					server.voiceSession.session = _data.session_id;
					server.voiceSession.self_mute = self_mute;
					server.voiceSession.self_deaf = self_deaf;
				}
			}
			break;
		case "VOICE_SERVER_UPDATE":
			serverID = _data.guild_id;
			server = client.servers[serverID];
			server.voiceSession.token = _data.token;
			server.voiceSession.severID = serverID;
			server.voiceSession.endpoint = _data.endpoint;
			joinVoiceChannel(client, server.voiceSession);
			break;
		case "GUILD_MEMBERS_CHUNK":
			serverID = _data.guild_id;
			if (!client.servers[serverID].members) client.servers[serverID].members = {};

			_data.members.forEach(function(member) {
				var uID = member.user.id;
				var members = client.servers[serverID].members;
				if (members[uID]) return;
				if (!client.users[uID]) client.users[uID] = new User(member.user);
				members[uID] = new Member(client, client.servers[serverID], member);
			});
			var all = Object.keys(client.servers).every(function(server) {
				server = client.servers[server];
				return server.member_count === Object.keys(server.members).length;
			});

			if (all) return client.emit("allUsers");
			break;
		case "GUILD_SYNC":
			_data.members.forEach(function(member) {
				var uID = member.user.id;
				if (!client.users[uID]) client.users[uID] = new User(member.user);
				client.servers[_data.id].members[uID] = new Member(client, client.servers[_data.id], member);
			});

			_data.presences.forEach(function(presence) {
				var uID = presence.user.id;
				var members = client.servers[_data.id].members;
				if (!members[uID]) return void(new User(presence.user));
				delete(presence.user);
				copyKeys(presence, members[uID]);
			});
			client.servers[_data.id].large = _data.large;
			break;
	}
	return emit(client, message);
}
599930
def handle(self, message):
        

        opcode = message['op']
        if opcode == 10:
            self.on_hello(message)
        elif opcode == 11:
            self.on_heartbeat(message)
        elif opcode == 0:
            self.on_message(message)
        else:
            logger.debug("Not a message we handle: OPCODE {}".format(opcode))
        return