# Link limiter check: 4 streams from the ARCHIVE (prod untouched), cap from MERGE_NET_CAP, ~45 s.
import importlib.util, subprocess, threading, time, sys
spec = importlib.util.spec_from_file_location('m', __import__('os').path.join(__import__('os').path.dirname(__import__('os').path.abspath(__file__)), '..', 'merge.py'))
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
L = m.LIMITER; L.start()
stop = time.time() + 45
def worker(i):
    lo = 120_000_000 + i * 3_000_000
    p = subprocess.Popen(['docker','exec',m.CT,'mysqldump','--defaults-extra-file=/secrets/arch.cnf','--single-transaction','--quick',
        '--no-create-info','--skip-triggers','--no-tablespaces','--set-gtid-purged=OFF','--column-statistics=0',
        '--compression-algorithms=zstd,zlib','--where',f'id between {lo} and {lo+2999999}','repricer','item_price_data'],
        stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
    while time.time() < stop:
        if not p.stdout.read(1 << 20): break
    p.kill(); p.wait()
ths = [threading.Thread(target=worker, args=(i,)) for i in range(4)]
[t.start() for t in ths]
rates = []
rx0=L.rx(); T0=time.time()
while time.time() < stop:
    time.sleep(5); rates.append(L.rate); st=subprocess.run(["docker","exec",m.CT,"sh","-c","for p in /proc/[0-9]*; do [ \"$(cat $p/comm 2>/dev/null)\" = mysqldump ] && grep -h State $p/status; done; true"],capture_output=True,text=True).stdout.split(); print("  states:", [x for x in st if len(x)==1])
    print(f"link {L.rate:6.1f} Mbit/s  {'PAUSED ' if not L.ok.is_set() else 'running'}  paused total {int(L.paused_sec)}s", flush=True)
[t.join() for t in ths]
m.signal_dumps('CONT')
subprocess.run(['docker','exec',m.CT,'sh','-c',m._SIG_SH % 'TERM'])
rxm=(L.rx()-rx0)*8/(time.time()-T0)/1e6
print(f"ACTUAL by the rx counter over the whole test: {rxm:.1f} Mbit/s")
print(f"RESULT: cap {m.NET_CAP_MBIT}, average link {sum(rates)/len(rates):.1f} Mbit/s, max {max(rates):.1f}, paused {int(L.paused_sec)}s")
