rack-devel archive mirror (unofficial) https://groups.google.com/group/rack-devel
 help / color / mirror / Atom feed
* big responses to slow clients: Rack vs PSGI
@ 2016-11-15 23:10 Eric Wong
  2016-12-15 20:07 ` James Tucker
  0 siblings, 1 reply; 5+ messages in thread
From: Eric Wong @ 2016-11-15 23:10 UTC (permalink / raw)
  To: rack-devel

I've been poking around in Plack/PSGI for Perl5 some months,
and am liking it in some ways more than Rack.

This only covers server-agnostic web applications; IMHO exposing
applications to server-specific stuff defeats the purpose of
these common specs.

In Rack, one major problem I have is streaming large responses
requires calling body.each synchronously.

For handling writing large responses to slow clients, this means
a Rack web server has 2 choices:


1) Block the calling Thread, Fiber, or process until the
   slow client can consume the input.  This hurts if you have
   many slow clients blocking all your threads.

      body.each { |buf| client.write(buf) }
      body.close

   Simple, but your app is at the mercy of how fast the client
   chooses to read the response.


2) Detect :wait_writable/:wait_readable (EAGAIN) when writing to
   the slow client and start buffering the response to memory or
   filesystem.

   This may lead to out-of-memory or out-of-storage conditions.

   nginx does this by default when proxying, so Rubyists are
   often unaware of this as it's common to use nginx in front
   of Rack servers for this purpose.

   Something like the following should handle slow clients
   without relying on nginx for buffering:

      tmp = nil
      body.each do |buf|
        if tmp
          tmp.write(buf)
        else
          # the optimistic case:
          case ret = client.write_nonblock(buf, exception: false)
          when :wait_writable, :wait_writable # EAGAIN :<
            tmp = Tempfile.new(ret.to_s)
            tmp.write(buf)
          when Integer
            exp = buf.bytesize
            if exp > ret # partial write :<
               tmp = Tempfile.new('partial')
               tmp.write(buf.byteslice(ret, exp - ret))
            end
          end
        end
      end

      if tmp
        server_specific_finish(client, tmp, body)
      else
        body.close if body.respond_to?(:close)
      end

   Gross; but smaller responses never get buffered this way.
   Any server-specific logic is still contained within the
   server itself, the Rack app may remain completely unaware
   of how a server handles slow clients.



PSGI allows at least two methods for streaming large responses.
I will only cover the "pull" method of getline+close below.

Naively, getline+close is usable like the Rack method 1) for
body.each:

      # Note: "getline" in Plack/PSGI is not required to return
      # a "line", so it can behave like "readpartial" in Ruby.
      while (defined(my $buf = $body->getline)) {
          $client->write($buf);
      }
      $body->close;

...With all the problems of blocking on the $client->write call.

On the surface, the difference between Rack and PSGI here is
minor.


However, "getline" yielding control to the server entirely has a
significant advantage over the Rack app calling a Proc provided
by the server: The server can stop calling $body->getline once
it detects a client is slow.

      # For the non-Perl-literate, it's pretty similar to Ruby.
      # Scalar variables are prefixed with $, and method.
      # calls are "$foo->METHOD" instead of "foo.METHOD" in Ruby
      # if/else/elsif/while all work the same as in Ruby
      # I will over-comment here assuming readers here are not
      # familiar with Perl.

      # Make client socking non-blocking, equivalent to
      # "IO#nonblock = true" in Ruby; normal servers would only
      # call this once after accept()-ing a connection.
      $client->blocking(0);

      my $blocked; # "my" declares a locally-scoped variable

      # "undef" in Perl are the equivalent of "nil" in Ruby,
      # so "defined" checks here are equivalent to Ruby nil checks
      while (defined(my $buf = $body->getline)) {
          # length($buf) is roughly buf.bytesize in Ruby;
          # I'll assume all data is binary since Perl's Unicode
          # handling confuses me no matter how many times I RTFM.
          my $exp = length($buf);

          # Behaves like Ruby IO#write_nonblock after the
          # $client->blocking(0) call above:
          my $ret = $client->syswrite($buf);

          # $ret is the number of bytes written on success:
          if (defined $ret) {
              if ($exp > $ret) { # partial write :<

                  # similar to String#byteslice in Ruby:
                  $blocked = substr($buf, $ret, $exp - $ret);

                  last; # break out of the while loop
              } # else { continue looping on while }

          # $! is the system errno from syswrite (see perlvar manpage
          # for details), $!{E****} just checks for $! matching the
          # particular error number.
          } elsif ($!{EAGAIN} || $!{EWOULDBLOCK}) {
              # A minor detail in this example:
              # this assignment is a copy, so equivalent to
              # "blocked = buf.dup" in Ruby, NOT merely
              # "blocked = buf".
              $blocked = $buf;

              last; # break out of the while loop
          } else {
              # Perl does not raise exceptions by default on
              # syscall errors, "die" is the standard exception
              # throwing mechanism:
              die "syswrite failed: $!\n";
          }
      }
      if (defined $blocked) {
          server_specific_finish($client, $blocked, $body);
      } else {
          $body->close;
      }

In both my Rack and PSGI examples, I have a reference to a
server_specific_finish call.  In the Rack example, this method
will stream the entire contents of tmp (a Tempfile) to the
client.

The problem is tmp in the Rack example may be as large as
the entire response.  This sucks for big responses.

In the PSGI example, the server_specific_finish call will only
have the contents of one buffer from $body->getline in memory at
a time.  The server will make further calls to $body->getline
when (and only when) the previous buffer is fully-written to the
client socket.  There is only one (app-provided) buffer in
server memory at once, not entire response.

Both server_specific_finish calls will call the "close" method
on the body when the entire response is written to the client
socket.  Delaying the "close" call may make sense for logging
purposes in Rack, even if body.each is long done running, and is
obviously required in the PSGI case since further "getline"
calls need to be made before "close".


The key difference is that in Rack, the data is "pushed" to the
server by the Rack app.  In PSGI, the app may instead ask the
server to "pull" that data.


Anyways, thanks for reading this far.  I just felt like writing
something down for future Rack/Ruby-related projects.  I'm not
sure if Rack can change without breaking all existing apps
and middlewares.

-- 

--- 
You received this message because you are subscribed to the Google Groups "Rack Development" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rack-devel+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

^ permalink raw reply	[flat|nested] 5+ messages in thread

end of thread, other threads:[~2017-06-01 22:05 UTC | newest]

Thread overview: 5+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2016-11-15 23:10 big responses to slow clients: Rack vs PSGI Eric Wong
2016-12-15 20:07 ` James Tucker
2016-12-24 23:15   ` Eric Wong
2016-12-27 16:00     ` James Tucker
2017-06-01 22:05   ` Eric Wong

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).