From 98e271051e93a1a10d0b4f45939f18e6cbe01367 Mon Sep 17 00:00:00 2001
From: Kyotaro Horiguchi <horiguchi.kyotaro@lab.ntt.co.jp>
Date: Wed, 22 Feb 2017 17:23:42 +0900
Subject: [PATCH 11/13] Some non-functional fixes.

Rename items of AsyncRequestState. Rewrite some comments, and some
struct members are renamed for readability.
---
 contrib/postgres_fdw/postgres_fdw.c | 66 +++++++++++++++++++------------------
 src/backend/executor/execAsync.c    | 62 ++++++++++++++++------------------
 src/backend/executor/nodeAppend.c   |  4 +--
 src/include/nodes/execnodes.h       |  8 ++---
 4 files changed, 69 insertions(+), 71 deletions(-)

diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index a52d54a..04f520b 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -129,17 +129,17 @@ enum FdwDirectModifyPrivateIndex
 /*
  * Connection private area structure.
  */
- typedef struct PgFdwConnspecate
+typedef struct PgFdwConnpriv
 {
 	ForeignScanState *current_owner;	/* The node currently running a query
 										 * on this connection*/
-} PgFdwConnspecate;
+} PgFdwConnpriv;
 
 /* Execution state base type */
 typedef struct PgFdwState
 {
 	PGconn	   *conn;			/* connection for the scan */
-	PgFdwConnspecate *connspec;	/* connection private memory */
+	PgFdwConnpriv *connpriv;	/* connection private memory */
 } PgFdwState;
 
 /*
@@ -385,8 +385,8 @@ static bool postgresIsForeignPathAsyncCapable(ForeignPath *path);
 static void postgresForeignAsyncRequest(EState *estate,
 							PendingAsyncRequest *areq);
 static bool postgresForeignAsyncConfigureWait(EState *estate,
-						    PendingAsyncRequest *areq,
-						    bool reinit);
+							PendingAsyncRequest *areq,
+							bool reinit);
 static void postgresForeignAsyncNotify(EState *estate,
 						   PendingAsyncRequest *areq);
 
@@ -1370,9 +1370,9 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags)
 	 * establish new connection if necessary.
 	 */
 	fsstate->s.conn = GetConnection(user, false);
-	fsstate->s.connspec = (PgFdwConnspecate *)
-		GetConnectionSpecificStorage(user, sizeof(PgFdwConnspecate));
-	fsstate->s.connspec->current_owner = NULL;
+	fsstate->s.connpriv = (PgFdwConnpriv *)
+		GetConnectionSpecificStorage(user, sizeof(PgFdwConnpriv));
+	fsstate->s.connpriv->current_owner = NULL;
 	fsstate->waiter = NULL;
 	fsstate->last_waiter = node;
 
@@ -1450,7 +1450,7 @@ postgresIterateForeignScan(ForeignScanState *node)
 		ForeignScanState *next_conn_owner = node;
 
 		/* This node has sent a query on this connection */
-		if (fsstate->s.connspec->current_owner == node)
+		if (fsstate->s.connpriv->current_owner == node)
 		{
 			/* Check if the result is available */
 			if (PQisBusy(fsstate->s.conn))
@@ -1498,7 +1498,7 @@ postgresIterateForeignScan(ForeignScanState *node)
 				fsstate->last_waiter = node;
 			}
 		}
-		else if (fsstate->s.connspec->current_owner)
+		else if (fsstate->s.connpriv->current_owner)
 		{
 			/*
 			 * Anyone else is holding this connection. Add myself to the tail
@@ -1507,7 +1507,7 @@ postgresIterateForeignScan(ForeignScanState *node)
 			 * shortcut to the last waiter.
 			 */
 			PgFdwScanState *conn_owner_state =
-				GetPgFdwScanState(fsstate->s.connspec->current_owner);
+				GetPgFdwScanState(fsstate->s.connpriv->current_owner);
 			ForeignScanState *last_waiter = conn_owner_state->last_waiter;
 			PgFdwScanState *last_waiter_state = GetPgFdwScanState(last_waiter);
 
@@ -1523,11 +1523,13 @@ postgresIterateForeignScan(ForeignScanState *node)
 			return ExecClearTuple(slot);
 		}
 
+		/* At this time no node is running on the connection */
+		Assert(GetPgFdwScanState(next_conn_owner)->s.connpriv->current_owner
+			   == NULL);
 		/*
 		 * Send the next request for the next owner of this connection if
 		 * needed.
 		 */
-
 		if (!GetPgFdwScanState(next_conn_owner)->eof_reached)
 		{
 			PgFdwScanState *next_owner_state =
@@ -1869,8 +1871,8 @@ postgresBeginForeignModify(ModifyTableState *mtstate,
 
 	/* Open connection; report that we'll create a prepared statement. */
 	fmstate->s.conn = GetConnection(user, true);
-	fmstate->s.connspec = (PgFdwConnspecate *)
-		GetConnectionSpecificStorage(user, sizeof(PgFdwConnspecate));
+	fmstate->s.connpriv = (PgFdwConnpriv *)
+		GetConnectionSpecificStorage(user, sizeof(PgFdwConnpriv));
 	fmstate->p_name = NULL;		/* prepared statement not made yet */
 
 	/* Deconstruct fdw_private data. */
@@ -2472,8 +2474,8 @@ postgresBeginDirectModify(ForeignScanState *node, int eflags)
 	 * establish new connection if necessary.
 	 */
 	dmstate->s.conn = GetConnection(user, false);
-	dmstate->s.connspec = (PgFdwConnspecate *)
-		GetConnectionSpecificStorage(user, sizeof(PgFdwConnspecate));
+	dmstate->s.connpriv = (PgFdwConnpriv *)
+		GetConnectionSpecificStorage(user, sizeof(PgFdwConnpriv));
 
 	/* Initialize state variable */
 	dmstate->num_tuples = -1;	/* -1 means not set yet */
@@ -2696,7 +2698,7 @@ estimate_path_cost_size(PlannerInfo *root,
 		List	   *local_param_join_conds;
 		StringInfoData sql;
 		PGconn	   *conn;
-		PgFdwConnspecate *connspec;
+		PgFdwConnpriv *connpriv;
 		Selectivity local_sel;
 		QualCost	local_cost;
 		List	   *fdw_scan_tlist = NIL;
@@ -2740,13 +2742,13 @@ estimate_path_cost_size(PlannerInfo *root,
 
 		/* Get the remote estimate */
 		conn = GetConnection(fpinfo->user, false);
-		connspec = GetConnectionSpecificStorage(fpinfo->user,
-												sizeof(PgFdwConnspecate));
-		if (connspec)
+		connpriv = GetConnectionSpecificStorage(fpinfo->user,
+												sizeof(PgFdwConnpriv));
+		if (connpriv)
 		{
 			PgFdwState tmpstate;
 			tmpstate.conn = conn;
-			tmpstate.connspec = connspec;
+			tmpstate.connpriv = connpriv;
 			vacate_connection(&tmpstate);
 		}
 
@@ -3181,7 +3183,7 @@ request_more_data(ForeignScanState *node)
 	char		sql[64];
 
 	/* The connection should be vacant */
-	Assert(fsstate->s.connspec->current_owner == NULL);
+	Assert(fsstate->s.connpriv->current_owner == NULL);
 
 	/*
 	 * If this is the first call after Begin or ReScan, we need to create the
@@ -3196,7 +3198,7 @@ request_more_data(ForeignScanState *node)
 	if (!PQsendQuery(conn, sql))
 		pgfdw_report_error(ERROR, NULL, conn, false, sql);
 
-	fsstate->s.connspec->current_owner = node;
+	fsstate->s.connpriv->current_owner = node;
 }
 
 /*
@@ -3210,7 +3212,7 @@ fetch_received_data(ForeignScanState *node)
 	MemoryContext oldcontext;
 
 	/* I should be the current connection owner */
-	Assert(fsstate->s.connspec->current_owner == node);
+	Assert(fsstate->s.connpriv->current_owner == node);
 
 	/*
 	 * We'll store the tuples in the batch_cxt.  First, flush the previous
@@ -3287,14 +3289,14 @@ fetch_received_data(ForeignScanState *node)
 	}
 	PG_CATCH();
 	{
-		fsstate->s.connspec->current_owner = NULL;
+		fsstate->s.connpriv->current_owner = NULL;
 		if (res)
 			PQclear(res);
 		PG_RE_THROW();
 	}
 	PG_END_TRY();
 
-	fsstate->s.connspec->current_owner = NULL;
+	fsstate->s.connpriv->current_owner = NULL;
 
 	MemoryContextSwitchTo(oldcontext);
 }
@@ -3305,16 +3307,16 @@ fetch_received_data(ForeignScanState *node)
 static void
 vacate_connection(PgFdwState *fdwstate)
 {
-	PgFdwConnspecate *connspec = fdwstate->connspec;
+	PgFdwConnpriv *connpriv = fdwstate->connpriv;
 	ForeignScanState *owner;
 
-	if (connspec == NULL || connspec->current_owner == NULL)
+	if (connpriv == NULL || connpriv->current_owner == NULL)
 		return;
 
 	/*
 	 * let the current connection owner read the result for the running query
 	 */
-	owner = connspec->current_owner;
+	owner = connpriv->current_owner;
 	fetch_received_data(owner);
 
 	/* Clear the waiting list */
@@ -3335,7 +3337,7 @@ static void
 absorb_current_result(ForeignScanState *node)
 {
 	PgFdwScanState *fsstate = GetPgFdwScanState(node);
-	ForeignScanState *owner = fsstate->s.connspec->current_owner;
+	ForeignScanState *owner = fsstate->s.connpriv->current_owner;
 
 	if (owner)
 	{
@@ -3344,7 +3346,7 @@ absorb_current_result(ForeignScanState *node)
 
 		while(PQisBusy(conn))
 			PQclear(PQgetResult(conn));
-		fsstate->s.connspec->current_owner = NULL;
+		fsstate->s.connpriv->current_owner = NULL;
 		fsstate->async_waiting = false;
 	}
 }
@@ -4785,7 +4787,7 @@ postgresForeignAsyncConfigureWait(EState *estate, PendingAsyncRequest *areq,
 	if (!reinit)
 		return true;
 
-	if (fsstate->s.connspec->current_owner == node)
+	if (fsstate->s.connpriv->current_owner == node)
 	{
 		AddWaitEventToSet(estate->es_wait_event_set,
 						  WL_SOCKET_READABLE, PQsocket(fsstate->s.conn),
diff --git a/src/backend/executor/execAsync.c b/src/backend/executor/execAsync.c
index a8e5f80..03ab811 100644
--- a/src/backend/executor/execAsync.c
+++ b/src/backend/executor/execAsync.c
@@ -99,14 +99,12 @@ ExecAsyncRequest(EState *estate, PlanState *requestor, int request_index,
 	areq->myindex = estate->es_num_pending_async;
 
 	/* Initialize the new request. */
+	areq->state = ASYNCREQ_IDLE;
 	areq->requestor = requestor;
 	areq->request_index = request_index;
 	areq->requestee = requestee;
 
-	/*
-	 * Give the requestee a chance to do whatever it wants.
-	 * Requst functions return true if a result is immediately available.
-	 */
+	/* Give the requestee a chance to do whatever it wants. */
 	switch (nodeTag(requestee))
 	{
 		case T_ForeignScanState:
@@ -118,10 +116,8 @@ ExecAsyncRequest(EState *estate, PlanState *requestor, int request_index,
 				(int) nodeTag(requestee));
 	}
 
-	/*
-	 * If a result is available, complete it immediately.
-	 */
-	if (areq->state == ASYNC_COMPLETE)
+	/* If a result is available, complete it immediately */
+	if (areq->state == ASYNCREQ_COMPLETE)
 	{
 		Assert(areq->result == NULL || IsA(areq->result, TupleTableSlot));
 
@@ -178,15 +174,16 @@ ExecAsyncEventLoop(EState *estate, PlanState *requestor, long timeout)
 		CHECK_FOR_INTERRUPTS();
 
 		/*
-		 * Check for events, but don't block if there notifications that
-		 * have not been delivered yet.
+		 * Check for events, but don't block if any undelivered notification
+		 * remains and process the notification immediately.
 		 */
 		if (estate->es_async_callback_pending > 0)
 			ExecAsyncEventWait(estate, 0);
 		else if (!ExecAsyncEventWait(estate, cur_timeout))
 			cur_timeout = 0;			/* Timeout was reached. */
-		else
+		else if (timeout > 0)
 		{
+			/* Exited before timeout. Calculate the remaining time. */
 			instr_time      cur_time;
 			long            cur_timeout = -1;
 
@@ -205,19 +202,15 @@ ExecAsyncEventLoop(EState *estate, PlanState *requestor, long timeout)
 			if (areq->requestee->instrument)
 				InstrStartNode(areq->requestee->instrument);
 
-			/* Skip it if not pending. */
-			if (areq->state == ASYNC_CALLBACK_PENDING)
+			/* Notify if the requestee is ready */
+			if (areq->state == ASYNCREQ_CALLBACK_PENDING)
 			{
-				/*
-				 * Mark it as no longer needing a callback.  We must do this
-				 * before dispatching the callback in case the callback resets
-				 * the flag.
-				 */
 				estate->es_async_callback_pending--;
 				ExecAsyncNotify(estate, areq);
 			}
 
-			if (areq->state == ASYNC_COMPLETE)
+			/* Deliver the acquired tuple to the requester */
+			if (areq->state == ASYNCREQ_COMPLETE)
 			{
 				any_node_done = true;
 				if (requestor == areq->requestor)
@@ -248,7 +241,9 @@ ExecAsyncEventLoop(EState *estate, PlanState *requestor, long timeout)
 				PendingAsyncRequest *head;
 				PendingAsyncRequest *tail = estate->es_pending_async[tidx];
 
-				if (tail->state == ASYNC_COMPLETE)
+				Assert(tail->state != ASYNCREQ_CALLBACK_PENDING);
+
+				if (tail->state == ASYNCREQ_COMPLETE)
 					continue;
 				head = estate->es_pending_async[hidx];
 				estate->es_pending_async[tidx] = head;
@@ -324,7 +319,7 @@ ExecAsyncEventWait(EState *estate, long timeout)
 	{
 		PendingAsyncRequest *areq = estate->es_pending_async[i];
 
-		if (areq->num_fd_events > 0)
+		if (areq->num_fd_events > 0 || areq->wants_process_latch)
 			added |= ExecAsyncConfigureWait(estate, areq, reinit);
 	}
 
@@ -358,9 +353,9 @@ ExecAsyncEventWait(EState *estate, long timeout)
 		{
 			PendingAsyncRequest *areq = w->user_data;
 
-			Assert(areq->state == ASYNC_WAITING);
+			Assert(areq->state == ASYNCREQ_WAITING);
 
-			areq->state = ASYNC_CALLBACK_PENDING;
+			areq->state = ASYNCREQ_CALLBACK_PENDING;
 			estate->es_async_callback_pending++;
 		}
 	}
@@ -377,8 +372,8 @@ ExecAsyncEventWait(EState *estate, long timeout)
 
 			if (areq->wants_process_latch)
 			{
-				Assert(areq->state == ASYNC_WAITING);
-				areq->state = ASYNC_CALLBACK_PENDING;
+				Assert(areq->state == ASYNCREQ_WAITING);
+				areq->state = ASYNCREQ_CALLBACK_PENDING;
 			}
 		}
 	}
@@ -453,11 +448,11 @@ ExecAsyncResponse(EState *estate, PendingAsyncRequest *areq)
 /*
  * An executor node should call this function to signal that it needs to wait
  * on one or more file descriptor events that can be registered on a
- * WaitEventSet, and possibly also on the process latch.  num_fd_events
- * should be the maximum number of file descriptor events that it will wish to
- * register.  force_reset should be true if the node can't reuse the
- * WaitEventSet it most recently initialized, for example because it needs to
- * drop a wait event from the set.
+ * WaitEventSet, and possibly also on process latch.  num_fd_events is the
+ * maximum number of file descriptor events that it will wish to register.
+ * force_reset should be true if the node can't reuse the WaitEventSet it most
+ * recently initialized, for example because it needs to drop a wait event
+ * from the set.
  */
 void
 ExecAsyncSetRequiredEvents(EState *estate, PendingAsyncRequest *areq,
@@ -467,7 +462,7 @@ ExecAsyncSetRequiredEvents(EState *estate, PendingAsyncRequest *areq,
 	estate->es_total_fd_events += num_fd_events - areq->num_fd_events;
 	areq->num_fd_events = num_fd_events;
 	areq->wants_process_latch = wants_process_latch;
-	areq->state = ASYNC_WAITING;
+	areq->state = ASYNCREQ_WAITING;
 
 	if (force_reset && estate->es_wait_event_set != NULL)
 	{
@@ -497,12 +492,13 @@ ExecAsyncRequestDone(EState *estate, PendingAsyncRequest *areq, Node *result)
 	 * need a callback to remove registered wait events.  It's not clear
 	 * that we would come out ahead, so use brute force for now.
 	 */
-	Assert(areq->state == ASYNC_IDLE || areq->state == ASYNC_CALLBACK_PENDING);
+	Assert(areq->state == ASYNCREQ_IDLE ||
+		   areq->state == ASYNCREQ_CALLBACK_PENDING);
 
 	if (areq->num_fd_events > 0 || areq->wants_process_latch)
 		ExecAsyncSetRequiredEvents(estate, areq, 0, false, true);
 
 	/* Save result and mark request as complete. */
 	areq->result = result;
-	areq->state = ASYNC_COMPLETE;
+	areq->state = ASYNCREQ_COMPLETE;
 }
diff --git a/src/backend/executor/nodeAppend.c b/src/backend/executor/nodeAppend.c
index 9c07b49..9293139 100644
--- a/src/backend/executor/nodeAppend.c
+++ b/src/backend/executor/nodeAppend.c
@@ -403,7 +403,7 @@ ExecAsyncAppendResponse(EState *estate, PendingAsyncRequest *areq)
 	TupleTableSlot *slot;
 
 	/* We shouldn't be called until the request is complete. */
-	Assert(areq->state == ASYNC_COMPLETE);
+	Assert(areq->state == ASYNCREQ_COMPLETE);
 
 	/* Our result slot shouldn't already be occupied. */
 	Assert(TupIsNull(node->ps.ps_ResultTupleSlot));
@@ -420,7 +420,7 @@ ExecAsyncAppendResponse(EState *estate, PendingAsyncRequest *areq)
 	if (TupIsNull(slot))
 		return;
 
-	/* Save result so we can return it. */
+	/* Set the next tuple from this requestee. */
 	Assert(node->as_nasyncresult < node->as_nasyncplans);
 	node->as_asyncresult[node->as_nasyncresult++] = slot;
 
diff --git a/src/include/nodes/execnodes.h b/src/include/nodes/execnodes.h
index 5afcd34..7a62eff 100644
--- a/src/include/nodes/execnodes.h
+++ b/src/include/nodes/execnodes.h
@@ -363,10 +363,10 @@ typedef struct ResultRelInfo
  */
 typedef enum AsyncRequestState
 {
-	ASYNC_IDLE,
-	ASYNC_WAITING,
-	ASYNC_CALLBACK_PENDING,
-	ASYNC_COMPLETE
+	ASYNCREQ_IDLE,						/* Nothing is requested */
+	ASYNCREQ_WAITING,					/* Waiting for events */
+	ASYNCREQ_CALLBACK_PENDING,			/* Having events to be processed */
+	ASYNCREQ_COMPLETE					/* Result is available */
 } AsyncRequestState;
 typedef struct PendingAsyncRequest
 {
-- 
2.9.2

