#!/usr/bin/env python3
"""Run the old clear-all race on a private Redis Unix socket; no shared keys."""
import subprocess
import tempfile
import time
from pathlib import Path


def main():
    print(subprocess.check_output(['redis-server','--version'],text=True).split(' sha=')[0])
    with tempfile.TemporaryDirectory(prefix='m22-redis-') as tmp:
        socket=str(Path(tmp)/'redis.sock')
        process=subprocess.Popen(['redis-server','--port','0','--unixsocket',socket,'--save','','--appendonly','no',
                                  '--dir',tmp],stdout=subprocess.DEVNULL,stderr=subprocess.PIPE)
        def command(*args):
            return subprocess.check_output(['redis-cli','--raw','-s',socket,*map(str,args)],text=True).strip()
        try:
            for _ in range(100):
                if Path(socket).exists() and command('PING')=='PONG':break
                time.sleep(.02)
            else:raise RuntimeError('private Redis did not start')
            command('ZADD','new:Ada',1,'Bo');command('ZADD','new:Ada',2,'Bo');command('ZADD','new:Ada',3,'Cy')
            print('snapshot through3: distinct senders='+command('ZCARD','new:Ada'))
            command('ZADD','new:Ada',4,'Dee');command('DEL','new:Ada')
            print('arrival4 then clear-all: count='+command('ZCARD','new:Ada'))
            command('ZADD','new:Ada',2,'Bo',3,'Cy',4,'Dee')
            command('ZREMRANGEBYSCORE','new:Ada','-inf',3)
            print('remove through3: senders='+command('ZRANGE','new:Ada',0,-1))
            command('ZADD','new:Ada',2,'Bo')
            print('delayed older update: ZCARD='+command('ZCARD','new:Ada')+'; ZCOUNT above ACK3='+command('ZCOUNT','new:Ada','(3','+inf'))
            # Timestamp equality cannot order these distinct accepted messages around ACK.
            command('ZADD','equal:Ada',100,'Bo',100,'Dee')
            command('ZREMRANGEBYSCORE','equal:Ada','-inf',100)
            print('equal timestamp100: remove-through100 removes both senders')
        finally:
            process.terminate();process.wait(timeout=5)


if __name__=='__main__':main()
