Plugs: Properly calculate Request/Response size in bytes?

Request: headers + body (lazy read?)?
Response: headers + body, but what about files? They are handled by cowboy directly and no after_send callback (well, I added one, but obviously content-length isn’t transferred from cowboy).

Actually sending files is dropped down to a low-level call to the kernel where the linux kernel itself streams the file to the socket after cowboy sends the headers. Cowboy just stats the file for the side. What are you trying to accomplish though?

Right, cowboy probably uses sendfile, but it must send content-length before. How to intercept it from cowboy?
I’m trying to do exactly what I asked :slight_smile: calculate request/response sizes in bytes :slight_smile:

Hmm, I’m curious, lets see how it does it.

So the call enters here:

Which gets passed to the Transport, which for HTTP will be ranch, so that gets passed to here:

The initial call to sendfile in cowboy takes the offset and bytes to send (looks efficient if you want to send only parts of a file, like a resume file header), so lets go ‘up’ the stack:

So plug takes the offset and byte size too for cowboy, let’s go higher up to the conn plug itself:

So plug defaults length to :all, lets follow it back up to the cowboy plug:

And here is where it tests if it is :all and if so it sets the length to the size of the file as from File.stat!. :slight_smile:

What are you needing it for? This can actually be an amazingly hard problem because proxies, front-end cachers, etc… can all change the request and headers in a large variety of ways…

For my Plugs instrumenters: GitHub - deadtrickster/prometheus-plugs: Prometheus.erl Elixir Plugs

Yep, I know some guy actually added these calculations: prometheus-plugs/lib/plug/utils.ex at 478bd29e1c0d5b668d73b596f1378b0ff9e43b1b · zanhsieh/prometheus-plugs · GitHub. Looks like unnecessary to repeat syscall there. But given luck of after_request callback I have no idea what to do.

So looks like I have to revive this thread. I think I can live without file stats but still, how to properly calculate regular request/response sizes (both headers and body)?

I’m still unsure how possible that is. You could calculate the part that Phoenix sends (say putting a plug right after your endpoint maybe?), but even that may not be accurate once it sends out as headers can be added and removed by a lot of things in a lot of ways…

What I expect(ed): a hook or event to be executed or fired just before the first byte sent. Headers should be already serialized to iolist and all is needed is iolist_size call. This is how I implemented this for Elli: https://github.com/elli-lib/elli/blob/develop/src/elli_http.erl#L595. Possibly it is too low-level for Plugs. And Cowboy is essentially uninstrumentable :(.