Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Фикс проверки столкновений при 0 длине шлейфа + Рефакторинги #314

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 50 additions & 27 deletions paperio/local_runner/clients.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,13 +147,41 @@ def send_message(self, t, d):
pass


class TcpClient(Client):
EXECUTION_LIMIT = datetime.timedelta(seconds=MAX_EXECUTION_TIME)
class BasicProxyClient(Client):
REQUEST_LIMIT = datetime.timedelta(seconds=REQUEST_MAX_TIME)
TOTAL_LIMIT = datetime.timedelta(seconds=MAX_EXECUTION_TIME)

def __init__(self):
self.execution_time = datetime.timedelta()
self.started_measure_time = None

def prepare_message_bytes(self, t, d):
msg = {
'type': t,
'params': d,
'time_left': round((self.TOTAL_LIMIT - self.execution_time).total_seconds() * 1000)
}
return '{}\n'.format(json.dumps(msg)).encode()

def begin_measure_time(self):
self.started_measure_time = datetime.datetime.now()

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Я понимаю, что это пришло из старого кода, но не лучше тогда уж time.perf_counter() использовать, раз такое масштабное причёсывание делается?


def end_measure_time(self):
request_time = (datetime.datetime.now() - self.started_measure_time)
if request_time > self.REQUEST_LIMIT:
raise Exception('request timeout error')

self.execution_time += request_time
if self.execution_time > self.TOTAL_LIMIT:
raise Exception('sum timeout error')


class TcpClient(BasicProxyClient):

def __init__(self, reader, writer):
super(TcpClient, self).__init__()
self.reader = reader
self.writer = writer
self.execution_time = datetime.timedelta()
self.solution_id = None

def save_log_to_disk(self, log, path):
Expand All @@ -178,31 +206,25 @@ async def set_solution_id(self):
return bool(self.solution_id)

def send_message(self, t, d):
msg = {
'type': t,
'params': d,
'time_left': round((self.EXECUTION_LIMIT-self.execution_time).total_seconds()*1000)
}
msg_bytes = '{}\n'.format(json.dumps(msg)).encode()
msg_bytes = self.prepare_message_bytes(t, d)
self.writer.write(msg_bytes)

async def get_command(self):
try:
before = datetime.datetime.now()
self.begin_measure_time()
#
z = await asyncio.wait_for(self.reader.readline(), timeout=REQUEST_MAX_TIME)
if not z:
raise ConnectionError('Connection closed')
self.execution_time += (datetime.datetime.now() - before)
if self.execution_time > self.EXECUTION_LIMIT:
raise Exception('sum timeout error')
#
self.end_measure_time()

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

По-хорошему должно быть внутри finally, мало ли кто для отладки захочет время посмотреть.

except asyncio.TimeoutError:
raise asyncio.TimeoutError('read timeout error')

try:
z = json.loads(z.decode())
return json.loads(z.decode())
except ValueError:
z = {'debug': 'cant pars json'}

return z
return {'debug': 'cant pars json'}

def close(self):
self.writer.close()
Expand All @@ -211,8 +233,10 @@ def get_solution_id(self):
return self.solution_id


class FileClient(Client):
class FileClient(BasicProxyClient):

def __init__(self, path_to_script, path_to_log=None):
super(FileClient, self).__init__()
self.process = Popen(path_to_script, stdout=PIPE, stdin=PIPE)
self.last_message = None
if path_to_log is None:
Expand All @@ -223,20 +247,19 @@ def __init__(self, path_to_script, path_to_log=None):
self.path_to_log = path_to_log

def send_message(self, t, d):
msg = {
'type': t,
'params': d
}
msg_bytes = '{}\n'.format(json.dumps(msg)).encode()

msg_bytes = self.prepare_message_bytes(t, d)
self.process.stdin.write(msg_bytes)
self.process.stdin.flush()

async def get_command(self):
try:
line = self.process.stdout.readline().decode('utf-8')
state = json.loads(line)
return state
self.begin_measure_time()
#
z = self.process.stdout.readline().decode('utf-8')
#
self.end_measure_time()

return json.loads(z)
except Exception as e:
return {'debug': str(e)}

Expand Down
Loading