-
Notifications
You must be signed in to change notification settings - Fork 139
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
Pro100AlexHell
wants to merge
4
commits into
MailRuChamps:master
Choose a base branch
from
Pro100AlexHell:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+243
−154
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
c69815d
Merge pull request #1 from MailRuChamps/master
Pro100AlexHell 48a8540
* check_loss_head_intersection = для проверки столкновений при 0 длин…
Pro100AlexHell e62a016
расчет времени и выдача 'time_left' в FileClient, рефакторинг (TcpCli…
Pro100AlexHell 6bbbeb2
Merge pull request #2 from MailRuChamps/master
Pro100AlexHell File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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() | ||
|
||
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): | ||
|
@@ -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() | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. По-хорошему должно быть внутри |
||
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() | ||
|
@@ -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: | ||
|
@@ -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)} | ||
|
||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Я понимаю, что это пришло из старого кода, но не лучше тогда уж
time.perf_counter()
использовать, раз такое масштабное причёсывание делается?