text: /* A simple event-driven programming library. Originally I wrote this code
   * for the Jim's event-loop (Jim is a Tcl interpreter) but later translated
   * it in form of a library for easy reuse.
   *
   * Copyright (c) 2006-2010, Salvatore Sanfilippo <antirez at gmail dot com>
   * All rights reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions are met:
   *
   *   * Redistributions of source code must retain the above copyright notice,
   *     this list of conditions and the following disclaimer.
   *   * Redistributions in binary form must reproduce the above copyright
   *     notice, this list of conditions and the following disclaimer in the
   *     documentation and/or other materials provided with the distribution.
   *   * Neither the name of Redis nor the names of its contributors may be used
   *     to endorse or promote products derived from this software without
   *     specific prior written permission.
   *
   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   * POSSIBILITY OF SUCH DAMAGE.
   */
  #include "async_event_handler.h"
  #include "async_event_epoll.h"
  
  /* create a new `event_loop` */
  ae_event_loop *
  ae_create_event_loop(int set_size) {
      ae_event_loop *event_loop;
  
      if ((event_loop = zmalloc(sizeof(ae_event_loop))) == NULL)
          goto err;
  
      if (set_size == -1)
          set_size = AE_DEFAULT_SET_SIZE;
      event_loop->set_size = set_size;
  
      event_loop->events = zmalloc(sizeof(ae_file_event) * event_loop->set_size);
      event_loop->fired = zmalloc(sizeof(ae_fired_event) * event_loop->set_size);
      if (event_loop->events == NULL || event_loop->fired == NULL)
          goto err;
      for (int i = 0; i < event_loop->set_size; i++)
          event_loop->events[i].mask = AE_NONE;
  
      event_loop->last_time = time(NULL);
      event_loop->time_event_head = NULL;
      event_loop->time_event_next_id = 0;
      event_loop->max_fd = -1;
      event_loop->before_sleep = NULL;
      event_loop->stop = 0;
  
      if (ae_api_create(event_loop) == AE_ERR)
          goto err;
  
      return event_loop;
  
  err:
      if (event_loop) {
          zfree(event_loop->events);
          zfree(event_loop->fired);
          zfree(event_loop);
      }
      return NULL;
  }
  
  /* destroy the `event_loop` */
  void
  ae_delete_event_loop(ae_event_loop *event_loop) {
      ae_api_free(event_loop);
      zfree(event_loop->events);
      zfree(event_loop->fired);
      zfree(event_loop);
  }
  
  /* disable the `event_loop` */
  void
  ae_stop(ae_event_loop *event_loop) {
      // TODO: use lock to protect it?
      event_loop->stop = 1;
  }
  
  /* add a new socket file descriptor event to `event_loop` */
  // TODO:  keep the fd in order from 0, 1, 2, 3 ...
  int
  ae_create_file_event(ae_event_loop *event_loop, int fd, int mask, ae_file_proc *proc, void *usr_data) {
      if (fd >= event_loop->set_size) {
          errno = ERANGE;
          return AE_ERR;
      }
  
      if (ae_api_add_event(event_loop, fd, mask) == AE_ERR)
          return AE_ERR;
  
      ae_file_event *fe = &event_loop->events[fd];
      fe->mask |= mask;
      if (mask & AE_READABLE)
          fe->r_file_proc = proc;
      if (mask & AE_WRITABLE)
          fe->w_file_proc = proc;
      fe->usr_data = usr_data;
  
      if (fd > event_loop->max_fd)
          event_loop->max_fd = fd;
  
      return AE_OK;
  }
  
  /* remove a socket file descriptor event from `event_loop` */
  int
  ae_delete_file_event(ae_event_loop *event_loop, int fd, int mask) {
      if (fd >= event_loop->set_size)
          return AE_OK;
  
      ae_file_event *fe = &event_loop->events[fd];
      if (fe->mask == AE_NONE)
          return AE_OK;
  
      if (ae_api_del_event(event_loop, fd, mask) == AE_ERR)
          return AE_ERR;
  
      fe->mask &= (~mask);
      if (fd == event_loop->max_fd && fe->mask == AE_NONE) {
          /* update the highest file descriptor currently registered */
          int j;
          for (j = event_loop->max_fd - 1; j >= 0; j--)
              if (event_loop->events[j].mask != AE_NONE)
                  break;
          event_loop->max_fd = j;
      }
  
      return AE_OK;
  }
  
  /* get all socket file descriptor events for `fd` */
  int
  ae_get_file_events(ae_event_loop *event_loop, int fd) {
      if (fd >= event_loop->set_size)
          return 0;
      return (&(event_loop->events[fd]))->mask;
  }
  
  static void
  ae_get_current_time(long *sec, long *ms) {
      struct timeval tv;
      gettimeofday(&tv, NULL);
      *sec = tv.tv_sec;
      *ms = tv.tv_usec / 1000;
  }
  
  static void
  ae_add_millisecs_to_now(long long add, long *sec, long *ms) {
      long cur_sec, cur_ms, when_sec, when_ms;
      ae_get_current_time(&cur_sec, &cur_ms);
      when_sec = cur_sec + add / 1000;
      when_ms = cur_ms + add % 1000;
      if (when_ms >= 1000) {
          when_sec++;
          when_ms -= 1000;
      }
      *sec = when_sec;
      *ms = when_ms;
  }
  
  /* add a new time-based event to `event_loop` */
  // TODO: use skiplist to insert/remove elems!!!
  long long
  ae_create_time_event(
    ae_event_loop *event_loop, long long ms, ae_time_proc *proc, void *usr_data, ae_event_finalizer *finalizer) {
      long long id = event_loop->time_event_next_id++;
      ae_time_event *te;
  
      if ((te = zmalloc(sizeof(ae_time_event))) == NULL)
          return AE_ERR;
      te->id = id;
      ae_add_millisecs_to_now(ms, &te->when_sec, &te->when_ms);
      te->time_proc = proc;
      te->finalizer = finalizer;
      te->usr_data = usr_data;
      te->next = event_loop->time_event_head;
      event_loop->time_event_head = te;
      return id;
  }
  
  /* remove the time-based event from `event_loop` */
  int
  ae_delete_time_event(ae_event_loop *event_loop, long long id) {
      if (event_loop->time_event_head == NULL)
          return AE_OK;
  
      ae_time_event *te = event_loop->time_event_head;
      while (te) {
          if (te->id == id) {
              /* mark as deleted */
              te->id = AE_DELETED_EVENT_ID;
              return AE_OK;
          }
          te = te->next;
      }
      return AE_ERR;
  }
  
  /* search the nearest time event to fire. */
  /* This operation is useful to know how many time events the select can be
   * put in sleep without to delay any event.
   *
   * If there are no time events, NULL is returned.
   *
   * Note that's O(N) since time events are unsorted.
   *
   * Possible optimizations:
   * 1) Insert the time event in order, so that the nearest is just the head.
   *    Much better but still insertion/deletion is O(N).
   * 2) Use skiplist to have this operation as O(1) and insertion/deletion
   *    as O(log(N)).
   */
  static ae_time_event *
  ae_search_nearest_time_event(ae_event_loop *event_loop) {
      ae_time_event *te = event_loop->time_event_head;
      ae_time_event *nearest = NULL;
  
      while (te) {
          if (!nearest || te->when_sec < nearest->when_sec
            || (te->when_sec == nearest->when_sec && te->when_ms < nearest->when_ms))
              nearest = te;
          te = te->next;
      }
      return nearest;
  }
  
  static int
  process_time_events(ae_event_loop *event_loop) {
      int processed = 0;
      ae_time_event *te, *prev_te;
  
      /* If the system clock is moved to the future, and then set back to the
       * right value, time events may be delayed in a random way. Often this
       * means that scheduled operations will not be performed soon enough.
       *
       * Here we try to detect system clock skews, and force all the time
       * events to be processed ASAP when this happens: the idea is that
       * processing events earlier is less dangerous than delaying them
       * indefinitely, and practice suggests it is.
       */
      time_t now = time(NULL);
      if (now < event_loop->last_time) {
          te = event_loop->time_event_head;
          while (te) {
              te->when_sec = 0;
              te = te->next;
          }
      }
      event_loop->last_time = now;
  
      prev_te = NULL;
      te = event_loop->time_event_head;
      long long max_id = event_loop->time_event_next_id - 1;
      while (te) {
          long now_sec, now_ms;
          long long id;
  
          /* remove events scheduled for deletion */
          if (te->id == AE_DELETED_EVENT_ID) {
              ae_time_event *next_te = te->next;
              if (prev_te == NULL)
                  event_loop->time_event_head = te->next;
              else
                  prev_te->next = te->next;
              if (te->finalizer != NULL)
                  te->finalizer(event_loop, te->usr_data);
              zfree(te);
              te = next_te;
              continue;
          }
  
          /* Make sure we don't process time events created by process_time_events
           * in this iteration.
           *
           * Note that this check is currently useless: we always add new timers
           * on the head, however if we change the implementation detail, this
           * check may be useful again: we keep it here for future defense.
           */
          if (te->id > max_id) {
              te = te->next;
              continue;
          }
  
          ae_get_current_time(&now_sec, &now_ms);
          if (now_sec > te->when_sec || (now_sec == te->when_sec && now_ms >= te->when_ms)) {
              int more_ms;
  
              id = te->id;
              more_ms = te->time_proc(event_loop, id, te->usr_data);
              processed++;
              if (more_ms != AE_NOMORE) {
                  ae_add_millisecs_to_now(more_ms, &te->when_sec, &te->when_ms);
              } else {
                  te->id = AE_DELETED_EVENT_ID;
              }
          }
          prev_te = te;
          te = te->next;
      }
  
      return processed;
  }
  
  /* Process every pending time event, then every pending file event
   * (that may be registered by time event callbacks just processed).
   * Without special flags the function sleeps until some file event
   * fires, or when the next time event occurs (if any).
   *
   * If flags is 0, the function does nothing and returns.
   * if flags has AE_ALL_EVENTS set, all the kind of events are processed.
   * if flags has AE_FILE_EVENTS set, file events are processed.
   * if flags has AE_TIME_EVENTS set, time events are processed.
   * if flags has AE_DONT_WAIT set, the function returns ASAP until all
   * the events that's possible to process without to wait are processed.
   */
  int
  ae_process_events(ae_event_loop *event_loop, int flags) {
      int processed = 0, ready_evs;
  
      /* nothing to do, return ASAP */
      if (!(flags & AE_TIME_EVENTS) && !(flags & AE_FILE_EVENTS))
          return processed;
  
      /* note that we want call select() even if there are no
       * file events to be processed as long as we want to process time
       * events, in order to sleep until the next time event is ready
       * to fire.
       */
      if (event_loop->max_fd != -1 || ((flags & AE_TIME_EVENTS) && !(flags & AE_DONT_WAIT))) {
          ae_time_event *shortest = NULL;
          struct timeval tv, *tvp;
  
          if ((flags & AE_TIME_EVENTS) && !(flags & AE_DONT_WAIT))
              shortest = ae_search_nearest_time_event(event_loop);
          if (shortest != NULL) {
              long now_sec, now_ms;
  
              ae_get_current_time(&now_sec, &now_ms);
              tvp = &tv;
  
              /* how many ms we need to wait for the next time event to fire */
              long long ms = (shortest->when_sec - now_sec) * 1000 + shortest->when_ms - now_ms;
  
              if (ms > 0) {
                  tvp->tv_sec = ms / 1000;
                  tvp->tv_usec = (ms % 1000) * 1000;
              } else {
                  tvp->tv_sec = 0;
                  tvp->tv_usec = 0;
              }
          } else {
              /* if we have to check for events but need to return ASAP because
               * of AE_DONT_WAIT we need to set the timeout to zero
               */
              if (flags & AE_DONT_WAIT) {
                  tv.tv_sec = tv.tv_usec = 0;
                  tvp = &tv;
              } else {
                  /* otherwise we can block to wait forever */
                  tvp = NULL;
              }
          }
  
          ready_evs = ae_api_poll(event_loop, tvp);
          for (int i = 0; i < ready_evs; i++) {
              int fd = event_loop->fired[i].fd;
              int mask = event_loop->fired[i].mask;
              ae_file_event *fe = &(event_loop->events[fd]);
              int rfired = 0;
  
              if (fe->mask & mask & AE_READABLE) {
                  rfired = 1;
                  fe->r_file_proc(event_loop, fd, fe->usr_data, mask);
              }
              if (fe->mask & mask & AE_WRITABLE) {
                  if (!rfired || fe->w_file_proc != fe->r_file_proc)
                      fe->w_file_proc(event_loop, fd, fe->usr_data, mask);
              }
              processed++;
          }
      }
  
      if (flags & AE_TIME_EVENTS)
          processed += process_time_events(event_loop);
  
      /* Return the number of processed file+time events */
      return processed;
  }
  
  /* run main routine of `event_loop` */
  void
  ae_main(ae_event_loop *event_loop) {
      event_loop->stop = 0;
      while (event_loop->stop == 0) {
          if (event_loop->before_sleep != NULL)
              event_loop->before_sleep(event_loop);
          ae_process_events(event_loop, AE_ALL_EVENTS);
      }
  }
  
  /* return currently used io api */
  char *
  ae_get_api_name(void) {
      return ae_api_name();
  }
  
  /* set `before_sleep` as ae_before_sleep_proc for `event_loop` */
  void
  ae_set_before_sleep_proc(ae_event_loop *event_loop, ae_before_sleep_proc *before_sleep) {
      event_loop->before_sleep = before_sleep;
  }
  
  int
  ae_get_set_size(ae_event_loop *event_loop) {
      return event_loop->set_size;
  }
  
  /* resize the maximum set size of the event loop. */
  /* If the requested set size is smaller than the current set size, but
   * there is already a file descriptor in use that is >= the requested
   * set size, AE_ERR is returned and the operation is not performed at
   * all.
   *
   * Otherwise AE_OK is returned and the operation is successful. */
  int
  ae_resize_set_size(ae_event_loop *event_loop, int new_set_size) {
      if (new_set_size == event_loop->set_size)
          return AE_OK;
      if (event_loop->max_fd >= new_set_size)
          return AE_ERR;
      if (ae_api_resize(event_loop, new_set_size) == -1)
          return AE_ERR;
  
      event_loop->events = zrealloc(event_loop->events, sizeof(ae_file_event) * new_set_size);
      event_loop->fired = zrealloc(event_loop->fired, sizeof(ae_fired_event) * new_set_size);
      event_loop->set_size = new_set_size;
  
      /* create new slots */
      for (int i = event_loop->max_fd + 1; i < new_set_size; i++)
          event_loop->events[i].mask = AE_NONE;
      return AE_OK;
  }