// File: /workspace/github_c_makefile_star2_O3/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, 0x8(%rsp)
movl $0x1, %eax
lock
xaddl %eax, 0xdd44(%rip)      # 0x185c8
testq %rdi, %rdi
movl %eax, 0x14(%rsp)
jne 0xa896
leaq 0xdbec(%rip), %rdi      # 0x18480
jmp 0xa89d
addq $0x88, %rdi
movq (%rdi), %rbx
incl 0x14(%rsp)
leaq 0x60(%rsp), %r14
leaq 0x8(%rsp), %r15
leaq 0x3a(%rsp), %r12
movq %rbx, %rdi
movq %r15, %rsi
movl $0xffffffff, %edx       # imm = 0xFFFFFFFF
callq 0xccdc
movq 0x8(%rsp), %rax
movl 0x20(%rax), %edi
cmpl $-0x1, %edi
je 0xaca1
testq %r14, %r14
leaq 0x60(%rsp), %rdx
setne %cl
cmpq %rdx, %r14
setne %bpl
andb %cl, %bpl
movq 0x8(%rax), %rcx
movl $0x1e, %edx
movq %r12, %rsi
movl $0x32, %r8d
callq 0xd4c5
cmpl $0x6e, %eax
jne 0xa99a
movq 0x8(%rsp), %rax
movq 0x8(%rax), %r13
testq %r13, %r13
je 0xa94e
movl $0x1, %edi
leaq 0x18(%rsp), %rsi
callq 0x2230
movabsq $0x431bde82d7b634db, %rax # imm = 0x431BDE82D7B634DB
mulq 0x20(%rsp)
imulq $0x3e8, 0x18(%rsp), %rax # imm = 0x3E8
shrq $0x12, %rdx
addq %rdx, %rax
cmpq %rax, %r13
jb 0xaadd
movq %rbx, %rdi
movq %r15, %rsi
callq 0xcb7c
testb %bpl, %bpl
je 0xa966
movq %r14, %rdi
callq 0x22c0
movl $0x1, %eax
lock
xaddq %rax, 0xdb14(%rip)      # 0x18488
movq %rbx, %rdi
movq %r15, %rsi
movl $0xffffffff, %edx       # imm = 0xFFFFFFFF
callq 0xccdc
movq 0x8(%rsp), %rax
movl 0x20(%rax), %edi
cmpl $-0x1, %edi
jne 0xa8e9
jmp 0xaca1
movl %eax, %r13d
testl %eax, %eax
jne 0xaa42
movq %r12, %rdi
callq 0xc8a8
leaq 0x42(%rsp), %rdi
callq 0xc8c5
movzwl 0x40(%rsp), %ebp
movl 0x3c(%rsp), %eax
shlq $0x20, %rbp
orq %rax, %rbp
movzbl 0x42(%rsp), %eax
subq %rax, %rbp
je 0xaa7a
cmpq $0x4001, %rbp           # imm = 0x4001
jb 0xa9f2
movq %rbp, %rdi
callq 0x22e0
movq %rax, %r14
testq %rax, %rax
je 0xac4c
movq 0x8(%rsp), %rax
movq %r14, %rsi
movq %rbp, %rdx
movl $0x32, %r8d
movl 0x20(%rax), %edi
movq 0x8(%rax), %rcx
callq 0xd4c5
testl %eax, %eax
je 0xaa7a
leaq 0xb8ae(%rip), %rcx      # 0x162c8
movl %eax, %r13d
cmpl $0x0, (%rcx)
js 0xab55
leaq 0xb8a3(%rip), %rax      # 0x162d0
xorl %edi, %edi
leaq 0x5878(%rip), %rsi      # 0x102ae
movq (%rax), %rcx
xorl %eax, %eax
callq *%rcx
jmp 0xab55
leaq 0xb87f(%rip), %rax      # 0x162c8
cmpl $0x0, (%rax)
js 0xab55
leaq 0xb877(%rip), %rax      # 0x162d0
xorl %edi, %edi
leaq 0x580c(%rip), %rsi      # 0x1026e
movl %r13d, %edx
movq (%rax), %r8
movq 0x8(%rsp), %rax
movl 0x20(%rax), %ecx
xorl %eax, %eax
callq *%r8
jmp 0xab55
testq %r14, %r14
je 0xac44
xorl %ecx, %ecx
leaq 0x42(%rsp), %rdi
movq %r14, %rsi
movq %rbp, %rdx
xorl %r8d, %r8d
xorl %r9d, %r9d
pushq $0x0
leaq 0x60(%rsp), %rax
pushq %rax
callq 0x535d
addq $0x10, %rsp
movq 0xdb0a(%rip), %rcx      # 0x185b8
movb $0x1, %r13b
testq %rcx, %rcx
je 0xabcc
movq 0x8(%rsp), %rdi
movzbl 0x47(%rsp), %esi
testl %eax, %eax
movl $0x1, %eax
movq 0x10(%rdi), %rdx
movq 0x28(%rdi), %rdi
cmovnel %eax, %esi
callq *%rcx
jmp 0xabcc
leaq 0xb7e4(%rip), %rax      # 0x162c8
movl $0xfffffffe, %r13d      # imm = 0xFFFFFFFE
cmpl $0x0, (%rax)
js 0xab55
leaq 0xb7da(%rip), %rax      # 0x162d0
movl $0x1, %edi
leaq 0x18(%rsp), %rsi
movq (%rax), %rax
movq %rax, 0x30(%rsp)
movq 0x8(%rsp), %rax
movq 0x8(%rax), %rcx
movq 0x18(%rax), %rbp
movq %rcx, 0x28(%rsp)
callq 0x2230
movabsq $0x431bde82d7b634db, %rax # imm = 0x431BDE82D7B634DB
imulq $0x3e8, 0x18(%rsp), %r8 # imm = 0x3E8
movq 0x28(%rsp), %rcx
xorl %edi, %edi
leaq 0x57ab(%rip), %rsi      # 0x102eb
mulq 0x20(%rsp)
shrq $0x12, %rdx
xorl %eax, %eax
addq %rdx, %r8
movq %rbp, %rdx
callq *0x30(%rsp)
leaq 0xb76c(%rip), %rax      # 0x162c8
cmpl $0x0, (%rax)
js 0xab80
leaq 0xb768(%rip), %rax      # 0x162d0
xorl %edi, %edi
leaq 0x57b6(%rip), %rsi      # 0x10327
movq (%rax), %rcx
movq 0x8(%rsp), %rax
movl 0x20(%rax), %edx
xorl %eax, %eax
callq *%rcx
movq 0x8(%rsp), %rax
movl 0x20(%rax), %edi
callq 0x2550
movq 0x8(%rsp), %rax
movl $0xffffffff, 0x20(%rax) # imm = 0xFFFFFFFF
movl $0x1, %eax
lock
xaddq %rax, 0xd8e9(%rip)      # 0x18490
movq 0xda02(%rip), %rax      # 0x185b0
testq %rax, %rax
je 0xabc5
movq 0x8(%rsp), %rcx
movl %r13d, %esi
movq 0x10(%rcx), %rdx
movq 0x28(%rcx), %rdi
callq *%rax
testq %r14, %r14
setne %r13b
movq 0x8(%rsp), %rax
movl 0x20(%rax), %esi
cmpl $-0x1, %esi
je 0xabec
movq 0x18(%rax), %rdi
movl $0x1, %edx
callq 0x844f
movq 0x8(%rsp), %rax
movq 0x18(%rax), %rdi
callq 0x8227
leaq 0xd8a4(%rip), %rax      # 0x184a0
movq %r15, %rsi
movq (%rax), %rdi
callq 0xcb7c
cmpl $-0x1, %eax
jne 0xac16
movq 0x8(%rsp), %rdi
callq 0x22c0
leaq 0x60(%rsp), %rax
cmpq %rax, %r14
sete %al
xorb $0x1, %r13b
orb %al, %r13b
jne 0xac32
movq %r14, %rdi
callq 0x22c0
movl 0xd874(%rip), %eax      # 0x184ac
cmpl 0x14(%rsp), %eax
jae 0xa8b3
jmp 0xac80
xorl %r13d, %r13d
xorl %r14d, %r14d
jmp 0xabcc
leaq 0xb675(%rip), %rax      # 0x162c8
movl $0xffffffff, %r13d      # imm = 0xFFFFFFFF
cmpl $0x0, (%rax)
js 0xac78
leaq 0xb66b(%rip), %rax      # 0x162d0
xorl %edi, %edi
leaq 0x4cb8(%rip), %rsi      # 0xf926
movq %rbp, %rdx
movq (%rax), %rcx
xorl %eax, %eax
callq *%rcx
xorl %r14d, %r14d
jmp 0xab55
movl $0xffffffff, %eax       # imm = 0xFFFFFFFF
lock
xaddl %eax, 0xd93b(%rip)      # 0x185c8
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