# Test streaming with replication delay

use strict;
use warnings;

use PostgresNode;
use TestLib;
use IPC::Run;
use Test::More;

my $golf = get_new_node('golf');

my $foxtrot = get_new_node('foxtrot');
$foxtrot->init(allows_streaming => 1, has_archiving => 1);
$foxtrot->append_conf('postgresql.conf', 'log_connections=on');
$foxtrot->start();

$foxtrot->safe_psql('postgres', 'select pg_create_physical_replication_slot(\'golf\')');

$foxtrot->backup('backup', replication_slot => 'golf');

$golf->init_from_backup($foxtrot, 'backup', has_streaming => 1, has_restoring => 1);
$golf->append_conf('recovery.conf', 'recovery_min_apply_delay = 1min');
$golf->append_conf('recovery.conf', 'primary_slot_name = \'golf\'');

system("pgbench", "-is10", "-p", $foxtrot->port);

my ($stat, $slots);
note("insert lsn: ". $foxtrot->safe_psql('postgres', 'select pg_current_wal_insert_lsn()'));
note("repl slot restart: ". $foxtrot->safe_psql('postgres', 'select restart_lsn from pg_replication_slots'));

$slots = $foxtrot->safe_psql('postgres', 'select slot_name,slot_type from pg_replication_slots');
ok($slots eq "golf|physical", "replication slot looks good");

# 80000 transactions should be enough to fill just over 3 segments

my $h = IPC::Run::start(['pgbench', '-R100', '-P1', '-T10000', $foxtrot->connstr('postgres')]);

sleep 62;

note("insert lsn: ". $foxtrot->safe_psql('postgres', 'select pg_current_wal_insert_lsn()'));
note("repl slot restart: ". $foxtrot->safe_psql('postgres', 'select restart_lsn from pg_replication_slots'));

$golf->start;

while (1) {
	$stat = $foxtrot->safe_psql('postgres', 'select * from pg_stat_replication');
	$slots = $foxtrot->safe_psql('postgres', 'select * from pg_replication_slots');
	ok(1, "stat: $stat repl: $slots");

	if ($stat ne '') {
		done_testing();
		exit 0;
	}

	sleep(10);
}
