2023-01-11 11:04:27 +01:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
# -*- coding: utf-8 -*-
|
2023-01-10 22:13:56 +01:00
|
|
|
import socket
|
|
|
|
from pathlib import Path
|
2023-01-11 11:04:27 +01:00
|
|
|
from typing import IO, AnyStr
|
2023-01-10 22:13:56 +01:00
|
|
|
|
|
|
|
from unix_sock_input import accept_loop_until_command_received
|
|
|
|
|
|
|
|
|
2023-01-11 11:04:27 +01:00
|
|
|
def receive_inform(in_pipe: IO[AnyStr],
|
|
|
|
socket_file: Path,
|
|
|
|
chunk_file_tmpl: Path) -> None:
|
2023-01-10 22:13:56 +01:00
|
|
|
"""
|
2023-01-11 11:04:27 +01:00
|
|
|
:param in_pipe:
|
2023-01-10 22:13:56 +01:00
|
|
|
:param chunk_file_tmpl:
|
|
|
|
:param cmd:
|
|
|
|
:param socket_file: Create a UNIX socket and wait for messages.
|
|
|
|
:return:
|
|
|
|
"""
|
|
|
|
print(f'Listening on socket {socket_file}')
|
|
|
|
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
|
|
sock.bind(str(socket_file))
|
|
|
|
sock.listen(1)
|
|
|
|
|
|
|
|
ct = 1
|
|
|
|
commands = [b'OK\n', b'EOF\n']
|
|
|
|
while True:
|
|
|
|
command = accept_loop_until_command_received(sock, commands)
|
2023-01-11 11:04:27 +01:00
|
|
|
if command not in commands:
|
|
|
|
raise ValueError("Invalid state")
|
|
|
|
|
|
|
|
chunk_file = chunk_file_tmpl.parent.joinpath(f'{chunk_file_tmpl.name}.{ct}')
|
|
|
|
chunk = chunk_file.read_bytes()
|
|
|
|
in_pipe.write(chunk)
|
|
|
|
# in_pipe.flush() # TODO: is this required?
|
|
|
|
chunk_file.unlink(missing_ok=False)
|
|
|
|
|
2023-01-10 22:13:56 +01:00
|
|
|
if command == b'OK\n':
|
|
|
|
ct += 1
|
|
|
|
elif command == b'EOF\n':
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
raise ValueError("Invalid state")
|
|
|
|
|
|
|
|
print(f'Closing socket {socket_file}')
|
|
|
|
sock.close()
|
|
|
|
socket_file.unlink(missing_ok=False)
|
|
|
|
|
2023-01-11 11:04:27 +01:00
|
|
|
in_pipe.flush()
|
|
|
|
|
|
|
|
# TODO: Has this any effect? On stdin probably yes!
|
|
|
|
in_pipe.close()
|