CASSCPP-6 The callbacks are not working in the newest version

patch by Bret McGuire; reviewed by Bret McGuire and Yifan Cai

Co-authored-by: toptobes <96998732+toptobes@users.noreply.github.com>
diff --git a/src/future.cpp b/src/future.cpp
index abbb6cf..aced1db 100644
--- a/src/future.cpp
+++ b/src/future.cpp
@@ -182,7 +182,7 @@
   }
   callback_ = callback;
   data_ = data;
-  if (is_set_) {
+  if (is_set()) {
     // Run the callback if the future is already set
     lock.unlock();
     callback(CassFuture::to(this), data);
@@ -191,7 +191,17 @@
 }
 
 void Future::internal_set(ScopedMutex& lock) {
-  is_set_ = true;
+
+  /* If the future has already been set (or another thread is already working on it) return immediately */
+  if (state_ != UNSTARTED) {
+    return;
+  }
+
+  state_ = STARTED;
+
+  /* CASSCPP-6 Identify the thread performing set so that wait() calls from this thread won't block */
+  set_caller_ = uv_thread_self();
+
   if (callback_) {
     Callback callback = callback_;
     void* data = data_;
@@ -199,6 +209,14 @@
     callback(CassFuture::to(this), data);
     lock.lock();
   }
+
+  /* CPP-987
+
+     Don't mark future as set until _after_ callbacks have run */
+  state_ = FINISHED;
+
+  set_caller_ = 0;
+
   // Broadcast after we've run the callback so that threads waiting
   // on this future see the side effects of the callback.
   uv_cond_broadcast(&cond_);
diff --git a/src/future.hpp b/src/future.hpp
index 92670fa..3080833 100644
--- a/src/future.hpp
+++ b/src/future.hpp
@@ -43,6 +43,8 @@
 
   enum Type { FUTURE_TYPE_GENERIC, FUTURE_TYPE_SESSION, FUTURE_TYPE_RESPONSE };
 
+  enum SetState { UNSTARTED, STARTED, FINISHED };
+
   struct Error : public Allocated {
     Error(CassError code, const String& message)
         : code(code)
@@ -53,9 +55,10 @@
   };
 
   Future(Type type)
-      : is_set_(false)
+      : state_(UNSTARTED)
       , type_(type)
-      , callback_(NULL) {
+      , callback_(NULL)
+      , set_caller_(0) {
     uv_mutex_init(&mutex_);
     uv_cond_init(&cond_);
   }
@@ -69,7 +72,7 @@
 
   bool ready() {
     ScopedMutex lock(&mutex_);
-    return is_set_;
+    return is_set();
   }
 
   virtual void wait() {
@@ -95,7 +98,7 @@
 
   bool set_error(CassError code, const String& message) {
     ScopedMutex lock(&mutex_);
-    if (!is_set_) {
+    if (is_unstarted()) {
       internal_set_error(code, message, lock);
       return true;
     }
@@ -105,26 +108,52 @@
   bool set_callback(Callback callback, void* data);
 
 protected:
-  bool is_set() const { return is_set_; }
+
+  bool is_unstarted() const { return state_ == UNSTARTED; }
+
+  bool is_set() const { return state_ == FINISHED; }
+
+  bool is_set_caller() {
+    /* CASSCPP-6 If we're being called by the thread setting the future just return immediately */
+    uv_thread_t me = uv_thread_self();
+    const uv_thread_t caller = set_caller_;
+    return set_caller_ && uv_thread_equal(&caller, &me);
+  }
 
   void internal_wait(ScopedMutex& lock) {
-    while (!is_set_) {
+    if (is_set_caller()) {
+      return;
+    }
+    while (!is_set()) {
       uv_cond_wait(&cond_, lock.get());
     }
   }
 
   bool internal_wait_for(ScopedMutex& lock, uint64_t timeout_us) {
-    if (!is_set_) {
+    if (is_set_caller()) {
+      return false;
+    }
+    if (!is_set()) {
       if (uv_cond_timedwait(&cond_, lock.get(), timeout_us * 1000) != 0) { // Expects nanos
         return false;
       }
     }
-    return is_set_;
+    return is_set();
   }
 
   void internal_set(ScopedMutex& lock);
 
   void internal_set_error(CassError code, const String& message, ScopedMutex& lock) {
+
+    /* If the future has already been set (or another thread is already working on it) return immediately.
+
+       We do not change the value of state_ to started because internal_set() performs a similar check and
+       doing so here would lead to an early return from that function.  We'll let the subsequent call to
+       internal_set() take care of any state updates. */
+    if (state_ != UNSTARTED) {
+      return;
+    }
+
     error_.reset(new Error(code, message));
     internal_set(lock);
   }
@@ -132,12 +161,13 @@
   uv_mutex_t mutex_;
 
 private:
-  bool is_set_;
+  SetState state_;
   uv_cond_t cond_;
   Type type_;
   ScopedPtr<Error> error_;
   Callback callback_;
   void* data_;
+  uv_thread_t set_caller_;
 
 private:
   DISALLOW_COPY_AND_ASSIGN(Future);
diff --git a/src/request_handler.hpp b/src/request_handler.hpp
index 5ed561b..14f524b 100644
--- a/src/request_handler.hpp
+++ b/src/request_handler.hpp
@@ -84,7 +84,10 @@
 
   bool set_response(Address address, const Response::Ptr& response) {
     ScopedMutex lock(&mutex_);
-    if (!is_set()) {
+    /* CASSCPP-6 We may still be able to get the mutex even if another thread is in internal_set() but in that case
+       future.state should have moved to at least STARTED... so we only proceed here if the future is still in an UNSTARTED
+       state.  */
+    if (is_unstarted()) {
       address_ = address;
       response_ = response;
       internal_set(lock);
@@ -101,7 +104,7 @@
 
   bool set_error_with_address(Address address, CassError code, const String& message) {
     ScopedMutex lock(&mutex_);
-    if (!is_set()) {
+    if (is_unstarted()) {
       address_ = address;
       internal_set_error(code, message, lock);
       return true;
@@ -112,7 +115,7 @@
   bool set_error_with_response(Address address, const Response::Ptr& response, CassError code,
                                const String& message) {
     ScopedMutex lock(&mutex_);
-    if (!is_set()) {
+    if (is_unstarted()) {
       address_ = address;
       response_ = response;
       internal_set_error(code, message, lock);
diff --git a/tests/src/unit/tests/test_future.cpp b/tests/src/unit/tests/test_future.cpp
index 1c1e0b3..85b0f57 100644
--- a/tests/src/unit/tests/test_future.cpp
+++ b/tests/src/unit/tests/test_future.cpp
@@ -34,8 +34,8 @@
 }
 
 void on_future_callback(CassFuture* future, void* data) {
-  bool* is_future_callback_called = static_cast<bool*>(data);
-  *is_future_callback_called = true;
+  bool* is_callback_called = static_cast<bool*>(data);
+  *is_callback_called = true;
 }
 
 void start_timer(void* arg) {
@@ -98,13 +98,13 @@
 }
 
 TEST(FutureUnitTest, Callback) {
-  bool is_future_callback_called = false;
+  bool is_callback_called = false;
   Future future(Future::FUTURE_TYPE_GENERIC);
-  ASSERT_TRUE(future.set_callback(&on_future_callback, &is_future_callback_called));
+  ASSERT_TRUE(future.set_callback(&on_future_callback, &is_callback_called));
 
-  ASSERT_FALSE(is_future_callback_called);
+  ASSERT_FALSE(is_callback_called);
   future.set();
-  ASSERT_TRUE(is_future_callback_called);
+  ASSERT_TRUE(is_callback_called);
   ASSERT_TRUE(future.ready());
 }
 
@@ -115,14 +115,57 @@
 }
 
 TEST(FutureUnitTest, CallbackAfterFutureIsSet) {
-  bool is_future_callback_called = false;
+  bool is_callback_called = false;
   Future future(Future::FUTURE_TYPE_GENERIC);
 
-  ASSERT_FALSE(is_future_callback_called);
+  ASSERT_FALSE(is_callback_called);
   future.set();
   ASSERT_TRUE(future.ready());
-  ASSERT_FALSE(is_future_callback_called);
+  ASSERT_FALSE(is_callback_called);
 
-  ASSERT_TRUE(future.set_callback(&on_future_callback, &is_future_callback_called));
-  ASSERT_TRUE(is_future_callback_called);
+  ASSERT_TRUE(future.set_callback(&on_future_callback, &is_callback_called));
+  ASSERT_TRUE(is_callback_called);
+}
+
+void callback_get_ready(CassFuture* future, void* data) {
+  bool* callback_flag = static_cast<bool*>(data);
+  *callback_flag = !future->ready();
+}
+
+TEST(FutureUnitTest, CallbacksRunBeforeFutureIsSet) {
+  bool callback_flag = false;
+  Future future(Future::FUTURE_TYPE_GENERIC);
+  ASSERT_TRUE(future.set_callback(&callback_get_ready, &callback_flag));
+
+  /* Confirm that ready() state in the callback is false before we do anything */
+  ASSERT_FALSE(callback_flag);
+  future.set();
+
+  /* Confirm that (a) we're getting the expected true value from ready() here and
+     (b) that callback_flag has moved from false to true.  This transition indicates
+     both that the callback ran and that ready() returned false when it did run. */
+  ASSERT_TRUE(future.ready());
+  ASSERT_TRUE(callback_flag);
+}
+
+void callback_with_wait(CassFuture* future, void* data) {
+  bool* callback_flag = static_cast<bool*>(data);
+  future->wait();
+  *callback_flag = true;
+}
+
+TEST(FutureUnitTest, WaitInCallbacksDoesNotIntroduceDeadlock) {
+  bool callback_flag = false;
+  Future future(Future::FUTURE_TYPE_GENERIC);
+  ASSERT_TRUE(future.set_callback(&callback_with_wait, &callback_flag));
+
+  /* Confirm that ready() state in the callback is false before we do anything */
+  ASSERT_FALSE(callback_flag);
+  future.set();
+
+  /* Confirm that (a) we're getting the expected true value from ready() here and
+     (b) that callback_flag has moved from false to true.  This transition indicates
+     both that the callback ran (which is enough to show that deadlock didn't occur). */
+  ASSERT_TRUE(future.ready());
+  ASSERT_TRUE(callback_flag);
 }