Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What to do with errors when streaming the body of an Http request

Tags:

http

protocols

How do I handle a server error in the middle of an Http message?

Assuming I already sent the header of the message and I am streaming the the body of the message, what do I do when I encounter an unexpected error.

I am also assuming this error was caused while generating the content and not a connection error.

(Greatly) Simplified Code:

// I can define any transfer encoding or header fields i need to. send(header);  // Sends the header to the Http client.  // Using an iterable instead of stream for code simplicity's sake. Iterable<String> stream = getBodyStream(); Iterator<String> iterator = stream.iterator();  while (iterator.hasNext()) {     String string;     try {        string = iterator.next();        catch (Throwable error) { // Oops! an error generating the content.         // What do i do here? (In regards to the Http protocol)     }      send(string); } 

Is there a way to tell the client the server failed and should either retry or abandon the connection or am I sool?

The code is greatly simplified but I am only asking in regards to the protocol and not the exact code.

Thank You

like image 235
user1964161 Avatar asked Mar 08 '13 23:03

user1964161


People also ask

What is streaming HTTP response?

HTTP Streaming is a push-style data transfer technique that allows a web server to continuously send data to a client over a single HTTP connection that remains open indefinitely.


1 Answers

One of the following should do it:

  1. Close the connection (reset or normal close)
  2. Write a malformed chunk (and close the connection) which will trigger client error
  3. Add a http trailer telling your client that something went wrong.
  4. Change your higher level protocol. Last piece of data you send is a hash or a length and the client knows to deal with it.
  5. If you can generate a hash or a length (in a custom header if using http chunks) of your content before you start sending you can send it in a header so your client knows what to expect.

It depends on what you want your client to do with the data (keep it or throw it away). You may not be able to make changes on the client side so the last option will not work for example.

Here is some explanation about the different ways to close. TCP option SO_LINGER (zero) - when it's required.

like image 76
jdb Avatar answered Sep 22 '22 05:09

jdb