Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 4cc0935045
Fetching contributors…

Cannot retrieve contributors at this time

file 85 lines (69 sloc) 2.159 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
#include "pomelo.h"

/**
* Pomelo package heartbeat parsing and processing.
*/

int pc__binary_write(pc_client_t *client, const char *data, size_t len,
                            uv_write_cb cb);

static void pc__heartbeat_req_cb(uv_write_t* req, int status);

int pc__heartbeat(pc_client_t *client) {
  uv_timer_stop(&client->timeout_timer);
  uv_timer_again(&client->heartbeat_timer);
  return 0;
}

int pc__heartbeat_req(pc_client_t *client) {
  if(PC_ST_WORKING != client->state) {
    return -1;
  }

  pc_buf_t buf = pc_pkg_encode(PC_PKG_HEARBEAT, NULL, 0);
  if(buf.len == -1) {
    fprintf(stderr, "Fail to encode heartbeat package.\n");
    goto error;
  }

  if(pc__binary_write(client, buf.base, buf.len, pc__heartbeat_req_cb)) {
    fprintf(stderr, "Fail to send heartbeat request.\n");
    goto error;
  }

  return 0;

error:
  if(buf.len != -1) free(buf.base);
  return -1;
}

void pc__heartbeat_cb(uv_timer_t* heartbeat_timer, int status) {
  uv_timer_stop(heartbeat_timer);
  pc_client_t *client = (pc_client_t *)heartbeat_timer->data;
  if(status == -1) {
    fprintf(stderr, "Pomelo heartbeat timer error, %s\n",
            uv_err_name(uv_last_error(heartbeat_timer->loop)));
    pc_client_stop(client);
    return;
  }

  if(pc__heartbeat_req(client)) {
    pc_client_stop(client);
    return;
  }

  uv_timer_again(&client->timeout_timer);
}

void pc__timeout_cb(uv_timer_t* timeout_timer, int status) {
  uv_timer_stop(timeout_timer);
  pc_client_t *client = (pc_client_t *)timeout_timer->data;
  if(status == -1) {
    fprintf(stderr, "Pomelo timeout timer error, %s\n",
            uv_err_name(uv_last_error(timeout_timer->loop)));
  } else {
    fprintf(stderr, "Pomelo client heartbeat timeout.\n");
  }
  pc_client_stop(client);
}

static void pc__heartbeat_req_cb(uv_write_t* req, int status) {
  void **data = (void **)req->data;
  pc_client_t *client = (pc_client_t *)data[0];
  char *base = (char *)data[1];

  free(base);
  free(data);
  free(req);

  if(status == -1) {
    fprintf(stderr, "Fail to write heartbeat async, %s.\n",
            uv_err_name(uv_last_error(client->uv_loop)));
    pc_client_stop(client);
  }
}
Something went wrong with that request. Please try again.