// File: /workspace/github_c_makefile_star2_O1/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 $0x4068, %rsp           # imm = 0x4068
movq $0x0, (%rsp)
movl $0x1, %eax
lock
xaddl %eax, 0xea28(%rip)      # 0x195c8
movl %eax, 0x14(%rsp)
testq %rdi, %rdi
jne 0xabb2
leaq 0xe8d0(%rip), %rdi      # 0x19480
jmp 0xabb9
addq $0x88, %rdi
incl 0x14(%rsp)
movq (%rdi), %rbx
leaq 0x60(%rsp), %r13
movq %rsp, %r15
leaq 0x3a(%rsp), %r12
movq $0x0, 0x8(%rsp)
movq %rbx, %rdi
movq %r15, %rsi
movl $0xffffffff, %edx       # imm = 0xFFFFFFFF
callq 0xd0df
movq (%rsp), %rax
movl 0x20(%rax), %edi
cmpl $-0x1, %edi
je 0xafb3
testq %r13, %r13
setne %cl
leaq 0x60(%rsp), %rdx
cmpq %rdx, %r13
setne %r14b
andb %cl, %r14b
movq 0x8(%rax), %rcx
movl $0x1e, %edx
movq %r12, %rsi
movl $0x32, %r8d
callq 0xd8bc
cmpl $0x6e, %eax
jne 0xacba
movq (%rsp), %rax
movq 0x8(%rax), %rbp
testq %rbp, %rbp
je 0xac6f
movl $0x1, %edi
leaq 0x18(%rsp), %rsi
callq 0x2230
movabsq $0x431bde82d7b634db, %rax # imm = 0x431BDE82D7B634DB
mulq 0x20(%rsp)
shrq $0x12, %rdx
imulq $0x3e8, 0x18(%rsp), %rax # imm = 0x3E8
addq %rdx, %rax
cmpq %rax, %rbp
jb 0xada5
movq %rbx, %rdi
movq %r15, %rsi
callq 0xcf8b
testb %r14b, %r14b
je 0xac87
movq %r13, %rdi
callq 0x22c0
movl $0x1, %eax
lock
xaddq %rax, 0xe7f3(%rip)      # 0x19488
movq %rbx, %rdi
movq %r15, %rsi
movl $0xffffffff, %edx       # imm = 0xFFFFFFFF
callq 0xd0df
movq (%rsp), %rax
movl 0x20(%rax), %edi
cmpl $-0x1, %edi
jne 0xac0b
jmp 0xafb3
movl %eax, %ebp
testl %eax, %eax
jne 0xad6f
movq %r12, %rdi
callq 0xccb0
leaq 0x42(%rsp), %rdi
callq 0xcccd
movl 0x3c(%rsp), %eax
movzwl 0x40(%rsp), %edx
shlq $0x20, %rdx
orq %rax, %rdx
movzbl 0x42(%rsp), %eax
subq %rax, %rdx
movb $0x1, %r14b
movq %rdx, 0x8(%rsp)
je 0xaec0
cmpq $0x4001, %rdx           # imm = 0x4001
jb 0xad20
movq 0x8(%rsp), %rdi
callq 0x22e0
movq 0x8(%rsp), %rdx
movq %rax, %r13
testq %rax, %rax
je 0xae22
movq (%rsp), %rax
movl 0x20(%rax), %edi
movq 0x8(%rax), %rcx
movq %r13, %rsi
movl $0x32, %r8d
callq 0xd8bc
testl %eax, %eax
je 0xaec0
movl %eax, %ebp
leaq 0xc57e(%rip), %rax      # 0x172c8
cmpl $0x0, (%rax)
js 0xae52
leaq 0xc576(%rip), %rax      # 0x172d0
movq (%rax), %rcx
xorl %edi, %edi
leaq 0x6528(%rip), %rsi      # 0x1128e
xorl %eax, %eax
callq *%rcx
jmp 0xae52
leaq 0xc552(%rip), %rax      # 0x172c8
cmpl $0x0, (%rax)
js 0xae52
leaq 0xc54a(%rip), %rax      # 0x172d0
movq (%rax), %r8
movq (%rsp), %rax
movl 0x20(%rax), %ecx
xorl %edi, %edi
leaq 0x64b5(%rip), %rsi      # 0x1124e
movl %ebp, %edx
xorl %eax, %eax
callq *%r8
jmp 0xae52
movl $0xfffffffe, %ebp       # imm = 0xFFFFFFFE
leaq 0xc517(%rip), %rax      # 0x172c8
cmpl $0x0, (%rax)
js 0xae52
leaq 0xc50f(%rip), %rax      # 0x172d0
movq (%rax), %r14
movq (%rsp), %rax
movq 0x8(%rax), %rcx
movq %rcx, 0x30(%rsp)
movq 0x18(%rax), %rax
movq %rax, 0x28(%rsp)
movl $0x1, %edi
leaq 0x18(%rsp), %rsi
callq 0x2230
movabsq $0x431bde82d7b634db, %rax # imm = 0x431BDE82D7B634DB
mulq 0x20(%rsp)
shrq $0x12, %rdx
imulq $0x3e8, 0x18(%rsp), %r8 # imm = 0x3E8
addq %rdx, %r8
xorl %edi, %edi
leaq 0x64ba(%rip), %rsi      # 0x112cb
movq 0x28(%rsp), %rdx
movq 0x30(%rsp), %rcx
xorl %eax, %eax
callq *%r14
jmp 0xae52
movl $0xffffffff, %ebp       # imm = 0xFFFFFFFF
leaq 0xc49a(%rip), %rax      # 0x172c8
cmpl $0x0, (%rax)
js 0xae4f
leaq 0xc496(%rip), %rax      # 0x172d0
movq (%rax), %rcx
xorl %edi, %edi
leaq 0x5ac2(%rip), %rsi      # 0x10908
movq 0x8(%rsp), %rdx
xorl %eax, %eax
callq *%rcx
xorl %r13d, %r13d
leaq 0xc46f(%rip), %rax      # 0x172c8
cmpl $0x0, (%rax)
js 0xae7c
leaq 0xc46b(%rip), %rax      # 0x172d0
movq (%rax), %rcx
movq (%rsp), %rax
movl 0x20(%rax), %edx
xorl %edi, %edi
leaq 0x648f(%rip), %rsi      # 0x11307
xorl %eax, %eax
callq *%rcx
movq (%rsp), %rax
movl 0x20(%rax), %edi
callq 0x2550
movq (%rsp), %rax
movl $0xffffffff, 0x20(%rax) # imm = 0xFFFFFFFF
movl $0x1, %eax
lock
xaddq %rax, 0xe5ef(%rip)      # 0x19490
movq 0xe708(%rip), %rax      # 0x195b0
testq %rax, %rax
je 0xaebd
movq (%rsp), %rcx
movq 0x10(%rcx), %rdx
movq 0x28(%rcx), %rdi
movl %ebp, %esi
callq *%rax
xorl %r14d, %r14d
testq %r13, %r13
sete %al
xorb $0x1, %r14b
orb %al, %r14b
jne 0xaf1e
leaq 0x42(%rsp), %rdi
movq %r13, %rsi
movq 0x8(%rsp), %rdx
xorl %ecx, %ecx
xorl %r8d, %r8d
xorl %r9d, %r9d
pushq $0x0
leaq 0x60(%rsp), %rax
pushq %rax
callq 0x53cb
addq $0x10, %rsp
movq 0xe6bc(%rip), %rcx      # 0x195b8
testq %rcx, %rcx
je 0xaf1e
testl %eax, %eax
movzbl 0x47(%rsp), %esi
movl $0x1, %eax
cmovnel %eax, %esi
movq (%rsp), %rax
movq 0x10(%rax), %rdx
movq 0x28(%rax), %rdi
callq *%rcx
movq (%rsp), %rax
movl 0x20(%rax), %esi
cmpl $-0x1, %esi
je 0xaf38
movq 0x18(%rax), %rdi
movl $0x1, %edx
callq 0x86b0
movq (%rsp), %rax
movq 0x18(%rax), %rdi
callq 0x8426
leaq 0xe554(%rip), %rax      # 0x194a0
movq (%rax), %rdi
movq %r15, %rsi
callq 0xcf8b
cmpl $-0x1, %eax
jne 0xaf65
movq (%rsp), %rdi
callq 0x22c0
testq %r13, %r13
sete %al
leaq 0x60(%rsp), %rcx
cmpq %rcx, %r13
sete %cl
orb %al, %cl
jne 0xaf82
movq %r13, %rdi
callq 0x22c0
movl 0xe524(%rip), %eax      # 0x194ac
cmpl 0x14(%rsp), %eax
jae 0xabd6
movl $0xffffffff, %eax       # imm = 0xFFFFFFFF
lock
xaddl %eax, 0xe629(%rip)      # 0x195c8
xorl %eax, %eax
addq $0x4068, %rsp           # imm = 0x4068
popq %rbx
popq %r12
popq %r13
popq %r14
popq %r15
popq %rbp
retq
xorl %edi, %edi
callq 0x24c0