#!/bin/bash
# added 2024-02-19 by rgerhards. Released under ASL 2.0
# This test is not meant to be executed independently. It just permits
# to be called by different drivers with different io buffer sizes.
# This in turn is needed to test some edge cases.
. ${srcdir:=.}/diag.sh init
skip_platform "SunOS" "This test is currently not supported on solaris due to too-different timing"
generate_conf
export NUMMESSAGES=2000
export OMFWD_TARGETFAIL_MAX_LOSS=250
export OMFWD_TARGETFAIL_MIN_RECEIVED=$((NUMMESSAGES - OMFWD_TARGETFAIL_MAX_LOSS))
export IMDIAG_INJECTMSG_DELAY_MS=10

# Start minitcpsrv with a forced receiver-side TCP session close and a
# temporary listener restart. The test verifies that omfwd retries and
# reconnects after that disruption.
export MINITCPSRV_EXTRA_OPTS="-D900 -B2 -a -S5"
start_minitcpsrvr $RSYSLOG_OUT_LOG  1

add_conf '
$MainMsgQueueTimeoutShutdown 10000
$MainMsgQueueDequeueBatchSize 100

global(allMessagesToStderr="on")

template(name="outfmt" type="string" string="%msg:F,58:2%\n")
module(load="builtin:omfwd" template="outfmt" iobuffer.maxSize="'$OMFWD_IOBUF_SIZE'")

if $msg contains "msgnum:" then {
	action(type="omfwd" target=["127.0.0.1"] port="'$MINITCPSRVR_PORT1'" protocol="tcp"
		pool.resumeInterval="2"
		action.reportsuspensioncontinuation="on"
		action.resumeRetryCount="-1" action.resumeInterval="3")
}
'
echo Note: intentionally not started any local TCP receiver!

# now do the usual run
startup

# Throttle imdiag injection so the forced close happens with less
# burst-created data already accepted by omfwd, the kernel, or TCP buffers.
# This keeps the scenario focused on retry/reconnect behavior. Some bounded
# loss is still expected because a successful send() only proves kernel
# acceptance, not that the receiver application persisted the message.
injectmsg
wait_file_lines "$RSYSLOG_OUT_LOG" "$OMFWD_TARGETFAIL_MIN_RECEIVED"
shutdown_when_empty
wait_shutdown
# note: minitcpsrv shuts down automatically if the connection is closed!

export SEQ_CHECK_OPTIONS=-d
# Permit bounded message loss in this forced receiver-close test. The
# pre-shutdown wait above keeps the assertion meaningful while the -m check
# accepts the expected loss window.
seq_check 0 $((NUMMESSAGES-1)) -m"$OMFWD_TARGETFAIL_MAX_LOSS"
exit_test
