69 lines
2.7 KiB
Python
69 lines
2.7 KiB
Python
"""Acceptance check on unique expiring Redis keys; no production keys are read or changed."""
|
|
import json
|
|
from pathlib import Path
|
|
import socket
|
|
import ssl
|
|
import subprocess
|
|
import uuid
|
|
|
|
container = 'moyi-test-moyi-api-1'
|
|
config = json.loads(subprocess.check_output(['docker', 'inspect', container]))[0]
|
|
env = dict(item.split('=', 1) for item in config['Config']['Env'] if '=' in item)
|
|
sock = socket.create_connection((env['MOYI_REDIS_HOST'], int(env.get('MOYI_REDIS_PORT', 6379))), 10)
|
|
if env.get('MOYI_REDIS_SSL', '').lower() == 'true':
|
|
sock = ssl.create_default_context().wrap_socket(sock, server_hostname=env['MOYI_REDIS_HOST'])
|
|
reader = sock.makefile('rb')
|
|
|
|
def response():
|
|
line = reader.readline()
|
|
if not line:
|
|
raise RuntimeError('Redis closed connection')
|
|
kind, text = line[:1], line[1:-2]
|
|
if kind == b'-':
|
|
raise RuntimeError('Redis rejected acceptance command')
|
|
if kind == b'+':
|
|
return text.decode()
|
|
if kind == b':':
|
|
return int(text)
|
|
if kind == b'$':
|
|
size = int(text)
|
|
if size < 0:
|
|
return None
|
|
value = reader.read(size)
|
|
reader.read(2)
|
|
return value
|
|
if kind == b'*':
|
|
return [response() for _ in range(int(text))]
|
|
raise RuntimeError('Unexpected Redis response')
|
|
|
|
def command(*parts):
|
|
values = [str(p).encode() for p in parts]
|
|
sock.sendall(b'*' + str(len(values)).encode() + b'\r\n' + b''.join(b'$' + str(len(v)).encode() + b'\r\n' + v + b'\r\n' for v in values))
|
|
return response()
|
|
|
|
if env.get('MOYI_REDIS_PASSWORD'):
|
|
args = ['AUTH']
|
|
if env.get('MOYI_REDIS_USERNAME'):
|
|
args.append(env['MOYI_REDIS_USERNAME'])
|
|
command(*args, env['MOYI_REDIS_PASSWORD'])
|
|
command('SELECT', int(env.get('MOYI_REDIS_DATABASE', 0)))
|
|
root = Path(__file__).resolve().parent
|
|
script = (root / 'acquire-slot.lua').read_text()
|
|
rate = (root / 'rate-limit.lua').read_text()
|
|
prefix = 'moyi:acceptance:' + uuid.uuid4().hex + ':'
|
|
keys = [prefix + 'user', prefix + 'rate']
|
|
try:
|
|
assert command('EVAL', script, 1, keys[0], 2, 60000, 'long-task') == 1
|
|
assert command('EVAL', script, 1, keys[0], 2, 1000, 'short-chat') == 1
|
|
assert command('PTTL', keys[0]) > 50000, 'Short chat shortened async lease'
|
|
assert command('EVAL', script, 1, keys[0], 2, 1000, 'third') == 0
|
|
assert command('ZREM', keys[0], 'short-chat') == 1
|
|
assert command('EVAL', script, 1, keys[0], 2, 1000, 'third') == 1
|
|
assert command('EVAL', rate, 1, keys[1], 1, 60000) == 0
|
|
assert command('EVAL', rate, 1, keys[1], 1, 60000) > 0
|
|
print('PASS: shared user concurrency, async lease lifetime, release and RPM on isolated keys')
|
|
finally:
|
|
command('DEL', *keys)
|
|
reader.close()
|
|
sock.close()
|