Skip to content

Add os.sendfile and os.splice support #2527

Description

@laurivosandi

Basically os.sendfile can be used to copy bytes from file descriptor to socket a'la to serve static files and os.splice can be used to copy bytes from pipe to socket. In both cases copying bytes to/from userspace Python process are bypassed.

This is just example snippet what I would like to do with Sanic:

from prometheus_client import Counter

counter_streamed_bytes = Counter(
    "backup_service_streamed_bytes",
    "Bytes transmitted")
counter_finished_streams = Counter(
    "backup_service_finished_streams",
    "Seemingly successfully finished streamings")
    ["exitcode"])

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'application/gzip')
        self.end_headers()
        cmd = "dd", "if=/dev/urandom", "bs=1024", "count=1024"
        proc = Popen(cmd, stdout=PIPE, stdin=PIPE)
        while True:
            bytes_sent = os.splice(proc.stdout.fileno(), self.wfile.fileno(), 65536)
            if not bytes_sent:
                break
            counter_streamed_bytes.inc(bytes_sent)
        proc.stdin.close()
        while True:
            buf = proc.stdout.read()
            if not buf:
                break
        proc.stdout.close()
        proc.wait()
        counter_finished_streams.labels(proc.returncode).inc()

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions