// File: /workspace/github_c_makefile_star2_O2/sharpyfox[P]citrusleaf-client/src/cl_async.c
// Function: async_receiver_fn
static void* 
async_receiver_fn(void *thdata)
{
	int 		rv = -1;
	bool 		network_error = false;
	cl_async_work	*workitem = NULL;
	cl_async_work	*tmpworkitem = NULL;
	as_msg 		msg;
	cf_queue	*q_to_use = NULL;
	cl_cluster_node	*thisnode = NULL;

	uint8_t		rd_stack_buf[STACK_BUF_SZ];	
	uint8_t		*rd_buf = rd_stack_buf;
	size_t		rd_buf_sz = 0;

	uint64_t	acktrid;
	uint64_t	starttime, endtime;
	int		progress_timeout_ms;
	unsigned int 	thread_id = cf_atomic32_incr(&g_thread_count);

	if (thdata == NULL) {
		q_to_use = g_cl_async_q;
	} else {
		thisnode = (cl_cluster_node *)thdata;
		q_to_use = thisnode->asyncwork_q;
	}
    
	//Infinite loop which keeps picking work items from the list and try to find the end result 
	while(1) {
		network_error = false;
#if ONEASYNCFD
		if(thisnode->dunned == true) {
			do {
				rv = cf_queue_pop(thisnode->asyncwork_q, &workitem, CF_QUEUE_NOWAIT);
				if (rv == CF_QUEUE_OK) {
					cl_cluster_node_put(thisnode);
					free(workitem);
				}
			} while (rv == CF_QUEUE_OK);

			//We want to delete all the workitems of this node
			shash_reduce_delete(g_cl_async_hashtab, cl_del_node_asyncworkitems, thisnode);
			break;
		}
#endif
		//This call will block if there is no element in the queue
		cf_queue_pop(q_to_use, &workitem, CF_QUEUE_FOREVER);

		// Check for thread shutdown message.
		if (workitem->fd == -1) {
			// Exit thread. Workitem will be freed in citrusleaf_async_shutdown().
			pthread_exit(NULL);
		}

		//TODO: What if the node gets dunned while this pop call is blocked ?
#if ONEASYNCFD
		//cf_debug("Elements remaining in this node's queue=%d, Hash table size=%d",
		//		cf_queue_sz(thisnode->asyncwork_q), shash_get_size(g_cl_async_hashtab));
#endif

		// If we have no progress in 50ms, we should move to the next workitem 
		// and revisit this workitem at a later stage
		progress_timeout_ms = DEFAULT_PROGRESS_TIMEOUT;

		// Read into this fine cl_msg, which is the short header
		rv = cf_socket_read_timeout(workitem->fd, (uint8_t *) &msg, sizeof(as_msg), workitem->deadline, progress_timeout_ms);
		if (rv) {
#if DEBUG
			cf_debug("Citrusleaf: error when reading header from server - rv %d fd %d", rv, workitem->fd);
#endif
			if (rv != ETIMEDOUT) {
				cf_error("Citrusleaf: error when reading header from server - rv %d fd %d",rv,workitem->fd);
				network_error = true;
				goto Error;
			} else {
				goto Retry;
			}

		}
#ifdef DEBUG_VERBOSE
		dump_buf("read header from cluster", (uint8_t *) &msg, sizeof(cl_msg));
#endif
		cl_proto_swap(&msg.proto);
		cl_msg_swap_header(&msg.m);

		// second read for the remainder of the message 
		rd_buf_sz =  msg.proto.sz  - msg.m.header_sz;
		if (rd_buf_sz > 0) {
			if (rd_buf_sz > sizeof(rd_stack_buf)) {
				rd_buf = malloc(rd_buf_sz);
				if (!rd_buf) {
					cf_error("malloc fail: trying %zu",rd_buf_sz);
					rv = -1; 
					goto Error; 
				}
			}

			rv = cf_socket_read_timeout(workitem->fd, rd_buf, rd_buf_sz, workitem->deadline, progress_timeout_ms);
			if (rv) {
				//We already read some part of the message before but failed to read the
				//remaining data for whatever reason (network error or timeout). We cannot
				//reread as we already read partial data. Declare this as error.
				cf_error("Timeout after reading the header but before reading the body");
				goto Error;
			}
#ifdef DEBUG_VERBOSE
			dump_buf("read body from cluster", rd_buf, rd_buf_sz);
#endif	
		}

		rv = CITRUSLEAF_OK;
		goto Ok;

Retry:
		//We are trying to postpone the reading
		if (workitem->deadline && workitem->deadline < cf_getms()) {
			cf_error("async receiver: out of time : node %s: deadline %"PRIu64" now %"PRIu64,
					workitem->node->name, workitem->deadline, cf_getms());
			//cf_error("async receiver: Workitem missed the final deadline");
			rv = CITRUSLEAF_FAIL_TIMEOUT;
			goto Error;
		} else {
			//We have time. Push the element back to the queue to be considered later
			cf_queue_push(q_to_use, &workitem);
		}

		//If we allocated memory in this loop, release it.
		if (rd_buf && (rd_buf != rd_stack_buf)) {
			free(rd_buf);
		}

		cf_atomic_int_incr(&g_async_stats.retries);

		continue;

Error:
		if (network_error == true) {
			/* 
			 * In case of Async work (for XDS), it may be extreme to
			 * dun a node in case of network error. We just cleanup
			 * things and retry to connect to the remote cluster.
			 * The network error may be a transient one.
			 */
		} 

#if ONEASYNCFD
//Do not close FD
#else
		//We do not know the state of FD. It may have pending data to be read.
		//We cannot reuse the FD. So, close it to be on safe side.
		cf_error("async receiver: Closing the fd %d because of error", workitem->fd);
		close(workitem->fd);
		workitem->fd = -1;
#endif
		cf_atomic_int_incr(&g_async_stats.dropouts);
		//Continue down with what we do during an Ok

		//Inform the caller that there is no response from the server for this workitem.
		//No response does not mean that the work is not done. The work might be 
		//successfully completed on the server side, we just didnt get response for it.
		if (g_fail_cb_fn) {
			g_fail_cb_fn(workitem->udata, rv, workitem->starttime);
		}
Ok:
		//rd_buf may not be there during an error condition.
		if (rd_buf && (rv == CITRUSLEAF_OK)) {
			//As of now, async functionality is there only for put call.
			//In put call, we do not get anything back other than the trid field.
			//So, just pass variable to get back the trid and ignore others.
			if (0 != cl_parse(&msg.m, rd_buf, rd_buf_sz, NULL, NULL, NULL, &acktrid, NULL)) {
				rv = CITRUSLEAF_FAIL_UNKNOWN;
			}
			else {
				rv = msg.m.result_code;
				if (workitem->trid != acktrid) {
#if ONEASYNCFD
					//It is likely that we may get response for a different trid.
					//Just delete the correct one from the queue 
					//put back the current workitem back in the queue.
					shash_get(g_cl_async_hashtab, &acktrid, &tmpworkitem);
					cf_queue_delete(q_to_use, &tmpworkitem, true);
					cf_queue_push(q_to_use, &workitem);
					//From now on workitem will be the one for which we got ack
					workitem = tmpworkitem;
#endif
#ifdef DEBUG
					cf_debug("Got reply for a different trid. Expected=%"PRIu64" Got=%"PRIu64" FD=%d",
							workitem->trid, acktrid, workitem->fd);
#endif
				}
			}

			if (g_success_cb_fn) {
				g_success_cb_fn(workitem->udata, rv, workitem->starttime);
			}
		}

		//Remember to put back the FD into the pool, if it is re-usable.
		if (workitem->fd != -1) {
			cl_cluster_node_fd_put(workitem->node, workitem->fd, true);
		}
		//Also decrement the reference count for this node
		cl_cluster_node_put(workitem->node);

#if ONEASYNCFD
		//Delete the item from the global hashtable
		if (shash_delete(g_cl_async_hashtab, &workitem->trid) != SHASH_OK)
		{
#if DEBUG
			cf_debug("Failure while trying to delete trid=%"PRIu64" from hashtable", workitem->trid);
#endif
		}
#endif

		//Push it back into the free pool. If the attempt fails, free it.
		if (cf_queue_push(g_cl_workitems_freepool_q, &workitem) == -1) {
			free(workitem);
		}

		//If we allocated memory in this loop, release it.
		if (rd_buf && (rd_buf != rd_stack_buf)) {
			free(rd_buf);
		}

		// Kick this thread out if its ID is greater than total
		if (thread_id > cf_atomic32_get(g_async_num_threads)) {
			cf_atomic32_decr(&g_thread_count);
			return NULL;
		}
	}//The infnite loop

	return NULL;
}

// Assembly:
pushq %rbp
pushq %r15
pushq %r14
pushq %r13
pushq %r12
pushq %rbx
subq $0x4048, %rsp           # imm = 0x4048
andq $0x0, (%rsp)
pushq $0x1
popq %rax
lock
xaddl %eax, 0xd679(%rip)      # 0x175c8
testq %rdi, %rdi
movl %eax, 0xc(%rsp)
jne 0x9f61
leaq 0xd521(%rip), %rdi      # 0x17480
jmp 0x9f68
addq $0x88, %rdi
movq (%rdi), %r14
incl 0xc(%rsp)
leaq 0x40(%rsp), %rbp
movq %rsp, %r12
leaq 0x1a(%rsp), %r13
testq %rbp, %rbp
leaq 0x40(%rsp), %rcx
setne %al
cmpq %rcx, %rbp
setne %bl
andb %al, %bl
movq %r14, %rdi
movq %r12, %rsi
pushq $-0x1
popq %rdx
callq 0xc163
movq (%rsp), %rax
movl 0x20(%rax), %edi
cmpl $-0x1, %edi
je 0xa2ba
movq 0x8(%rax), %rcx
movq %r13, %rsi
pushq $0x1e
popq %rdx
pushq $0x32
popq %r8
callq 0xc8d4
cmpl $0x6e, %eax
jne 0xa005
movq (%rsp), %rax
movq 0x8(%rax), %r15
testq %r15, %r15
je 0x9fe0
callq 0xa498
cmpq %rax, %r15
jb 0xa140
movq %r14, %rdi
movq %r12, %rsi
callq 0xc01b
testb %bl, %bl
je 0x9ff7
movq %rbp, %rdi
callq 0x22c0
pushq $0x1
popq %rax
lock
xaddq %rax, 0xd485(%rip)      # 0x17488
jmp 0x9f8f
movl %eax, %r15d
testl %eax, %eax
jne 0xa0aa
movq %r13, %rdi
callq 0xbd64
leaq 0x22(%rsp), %rdi
callq 0xbd80
movzwl 0x20(%rsp), %ebx
movl 0x1c(%rsp), %eax
shlq $0x20, %rbx
orq %rax, %rbx
movzbl 0x22(%rsp), %eax
subq %rax, %rbx
je 0xa0e1
cmpq $0x4001, %rbx           # imm = 0x4001
jb 0xa05d
movq %rbx, %rdi
callq 0x22e0
movq %rax, %rbp
testq %rax, %rax
je 0xa26c
movq (%rsp), %rax
movq %rbp, %rsi
movq %rbx, %rdx
movl 0x20(%rax), %edi
movq 0x8(%rax), %rcx
pushq $0x32
popq %r8
callq 0xc8d4
testl %eax, %eax
je 0xa0e1
leaq 0xb246(%rip), %rcx      # 0x152c8
movl %eax, %r15d
cmpl $0x0, (%rcx)
js 0xa188
leaq 0xb23b(%rip), %rax      # 0x152d0
xorl %edi, %edi
leaq 0x5220(%rip), %rsi      # 0xf2be
movq (%rax), %rcx
xorl %eax, %eax
callq *%rcx
jmp 0xa188
leaq 0xb217(%rip), %rax      # 0x152c8
cmpl $0x0, (%rax)
js 0xa188
leaq 0xb20f(%rip), %rax      # 0x152d0
xorl %edi, %edi
leaq 0x51b4(%rip), %rsi      # 0xf27e
movl %r15d, %edx
movq (%rax), %r8
movq (%rsp), %rax
movl 0x20(%rax), %ecx
xorl %eax, %eax
callq *%r8
jmp 0xa188
testq %rbp, %rbp
je 0xa266
xorl %ecx, %ecx
leaq 0x22(%rsp), %rdi
movq %rbp, %rsi
movq %rbx, %rdx
xorl %r8d, %r8d
xorl %r9d, %r9d
pushq $0x0
leaq 0x40(%rsp), %rax
pushq %rax
callq 0x4ec1
addq $0x10, %rsp
movq 0xd4a3(%rip), %rcx      # 0x175b8
movb $0x1, %bl
testq %rcx, %rcx
je 0xa1f5
movzbl 0x27(%rsp), %esi
testl %eax, %eax
pushq $0x1
popq %rax
movq (%rsp), %rdi
cmovnel %eax, %esi
movq 0x10(%rdi), %rdx
movq 0x28(%rdi), %rdi
callq *%rcx
jmp 0xa1f5
leaq 0xb181(%rip), %rax      # 0x152c8
cmpl $0x0, (%rax)
js 0xa184
leaq 0xb17d(%rip), %rax      # 0x152d0
movq (%rax), %rax
movq (%rsp), %rcx
movq 0x8(%rcx), %rbx
movq 0x18(%rcx), %r15
movq %rax, 0x10(%rsp)
callq 0xa498
movq %rax, %r8
xorl %edi, %edi
leaq 0x5183(%rip), %rsi      # 0xf2fb
movq %r15, %rdx
movq %rbx, %rcx
xorl %eax, %eax
callq *0x10(%rsp)
pushq $-0x2
popq %r15
leaq 0xb139(%rip), %rax      # 0x152c8
cmpl $0x0, (%rax)
js 0xa1b2
leaq 0xb135(%rip), %rax      # 0x152d0
xorl %edi, %edi
leaq 0x5193(%rip), %rsi      # 0xf337
movq (%rax), %rcx
movq (%rsp), %rax
movl 0x20(%rax), %edx
xorl %eax, %eax
callq *%rcx
movq (%rsp), %rax
movl 0x20(%rax), %edi
callq 0x2550
movq (%rsp), %rax
orl $-0x1, 0x20(%rax)
pushq $0x1
popq %rax
lock
xaddq %rax, 0xd2be(%rip)      # 0x17490
movq 0xd3d7(%rip), %rax      # 0x175b0
testq %rax, %rax
je 0xa1ef
movq (%rsp), %rcx
movl %r15d, %esi
movq 0x10(%rcx), %rdx
movq 0x28(%rcx), %rdi
callq *%rax
testq %rbp, %rbp
setne %bl
movq (%rsp), %rax
movl 0x20(%rax), %esi
cmpl $-0x1, %esi
je 0xa211
movq 0x18(%rax), %rdi
pushq $0x1
popq %rdx
callq 0x7d64
movq (%rsp), %rax
movq 0x18(%rax), %rdi
callq 0x7b74
leaq 0xd27f(%rip), %rax      # 0x174a0
movq %r12, %rsi
movq (%rax), %rdi
callq 0xc01b
cmpl $-0x1, %eax
jne 0xa23a
movq (%rsp), %rdi
callq 0x22c0
leaq 0x40(%rsp), %rax
cmpq %rax, %rbp
sete %al
xorb $0x1, %bl
orb %al, %bl
jne 0xa254
movq %rbp, %rdi
callq 0x22c0
movl 0xd252(%rip), %eax      # 0x174ac
cmpl 0xc(%rsp), %eax
jae 0x9f7c
jmp 0xa29b
xorl %ebx, %ebx
xorl %ebp, %ebp
jmp 0xa1f5
leaq 0xb055(%rip), %rax      # 0x152c8
cmpl $0x0, (%rax)
js 0xa292
leaq 0xb051(%rip), %rax      # 0x152d0
xorl %edi, %edi
leaq 0x469e(%rip), %rsi      # 0xe926
movq %rbx, %rdx
movq (%rax), %rcx
xorl %eax, %eax
callq *%rcx
xorl %ebp, %ebp
pushq $-0x1
jmp 0xa186
pushq $-0x1
popq %rax
lock
xaddl %eax, 0xd322(%rip)      # 0x175c8
xorl %eax, %eax
addq $0x4048, %rsp           # imm = 0x4048
popq %rbx
popq %r12
popq %r13
popq %r14
popq %r15
popq %rbp
retq
xorl %edi, %edi
callq 0x24c0