== Streams

There are several objects in Vert.x that allow items to be read from and written.

In previous versions the streams.adoc package was manipulating `link:../../jsdoc/buffer-Buffer.html[Buffer]`
objects exclusively. From now, streams are not coupled to buffers anymore and they work with any kind of objects.

In Vert.x, write calls return immediately, and writes are queued internally.

It's not hard to see that if you write to an object faster than it can actually write the data to
its underlying resource, then the write queue can grow unbounded - eventually resulting in
memory exhaustion.

To solve this problem a simple flow control (_back-pressure_) capability is provided by some objects in the Vert.x API.

Any flow control aware object that can be _written-to_ implements `link:../../jsdoc/write_stream-WriteStream.html[WriteStream]`,
while any flow control object that can be _read-from_ is said to implement `link:../../jsdoc/read_stream-ReadStream.html[ReadStream]`.

Let's take an example where we want to read from a `ReadStream` then write the data to a `WriteStream`.

A very simple example would be reading from a `link:../../jsdoc/net_socket-NetSocket.html[NetSocket]` then writing back to the
same `NetSocket` - since `NetSocket` implements both `ReadStream` and `WriteStream`. Note that this works
between any `ReadStream` and `WriteStream` compliant object, including HTTP requests, HTTP responses,
async files I/O, WebSockets, etc.

A naive way to do this would be to directly take the data that has been read and immediately write it
to the `NetSocket`:

[source,js]
----
var server = vertx.createNetServer({
  "port" : 1234,
  "host" : "localhost"
});
server.connectHandler(function (sock) {
  sock.handler(function (buffer) {
    // Write the data straight back
    sock.write(buffer);
  });
}).listen();

----

There is a problem with the example above: if data is read from the socket faster than it can be
written back to the socket, it will build up in the write queue of the `NetSocket`, eventually
running out of RAM. This might happen, for example if the client at the other end of the socket
wasn't reading fast enough, effectively putting back-pressure on the connection.

Since `NetSocket` implements `WriteStream`, we can check if the `WriteStream` is full before
writing to it:

[source,js]
----
var server = vertx.createNetServer({
  "port" : 1234,
  "host" : "localhost"
});
server.connectHandler(function (sock) {
  sock.handler(function (buffer) {
    if (!sock.writeQueueFull()) {
      sock.write(buffer);
    }
  });

}).listen();

----

This example won't run out of RAM but we'll end up losing data if the write queue gets full. What we
really want to do is pause the `NetSocket` when the write queue is full:

[source,js]
----
var server = vertx.createNetServer({
  "port" : 1234,
  "host" : "localhost"
});
server.connectHandler(function (sock) {
  sock.handler(function (buffer) {
    sock.write(buffer);
    if (sock.writeQueueFull()) {
      sock.pause();
    }
  });
}).listen();

----

We're almost there, but not quite. The `NetSocket` now gets paused when the file is full, but we also need to unpause
it when the write queue has processed its backlog:

[source,js]
----
var server = vertx.createNetServer({
  "port" : 1234,
  "host" : "localhost"
});
server.connectHandler(function (sock) {
  sock.handler(function (buffer) {
    sock.write(buffer);
    if (sock.writeQueueFull()) {
      sock.pause();
      sock.drainHandler(function (done) {
        sock.resume();
      });
    }
  });
}).listen();

----

And there we have it. The `link:../../jsdoc/write_stream-WriteStream.html#drainHandler[drainHandler]` event handler will
get called when the write queue is ready to accept more data, this resumes the `NetSocket` that
allows more data to be read.

Wanting to do this is quite common while writing Vert.x applications, so we provide a helper class
called `link:../../jsdoc/pump-Pump.html[Pump]` that does all of this hard work for you.
You just feed it the `ReadStream` plus the `WriteStream` then start it:

[source,js]
----
var Pump = require("vertx-js/pump");
var server = vertx.createNetServer({
  "port" : 1234,
  "host" : "localhost"
});
server.connectHandler(function (sock) {
  Pump.pump(sock, sock).start();
}).listen();

----

This does exactly the same thing as the more verbose example.

Let's now look at the methods on `ReadStream` and `WriteStream` in more detail:

=== ReadStream

`ReadStream` is implemented by `link:../../jsdoc/http_client_response-HttpClientResponse.html[HttpClientResponse]`, `link:../../jsdoc/datagram_socket-DatagramSocket.html[DatagramSocket]`,
`link:../../jsdoc/http_client_request-HttpClientRequest.html[HttpClientRequest]`, `link:../../jsdoc/http_server_file_upload-HttpServerFileUpload.html[HttpServerFileUpload]`,
`link:../../jsdoc/http_server_request-HttpServerRequest.html[HttpServerRequest]`, `link:../../jsdoc/http_server_request_stream-HttpServerRequestStream.html[HttpServerRequestStream]`,
`link:../../jsdoc/message_consumer-MessageConsumer.html[MessageConsumer]`, `link:../../jsdoc/net_socket-NetSocket.html[NetSocket]`, `link:../../jsdoc/net_socket_stream-NetSocketStream.html[NetSocketStream]`,
`link:../../jsdoc/web_socket-WebSocket.html[WebSocket]`, `link:../../jsdoc/web_socket_stream-WebSocketStream.html[WebSocketStream]`, `link:../../jsdoc/timeout_stream-TimeoutStream.html[TimeoutStream]`,
`link:../../jsdoc/async_file-AsyncFile.html[AsyncFile]`.

Functions:

- `link:../../jsdoc/read_stream-ReadStream.html#handler[handler]`:
set a handler which will receive items from the ReadStream.
- `link:../../jsdoc/read_stream-ReadStream.html#pause[pause]`:
pause the handler. When paused no items will be received in the handler.
- `link:../../jsdoc/read_stream-ReadStream.html#resume[resume]`:
resume the handler. The handler will be called if any item arrives.
- `link:../../jsdoc/read_stream-ReadStream.html#exceptionHandler[exceptionHandler]`:
Will be called if an exception occurs on the ReadStream.
- `link:../../jsdoc/read_stream-ReadStream.html#endHandler[endHandler]`:
Will be called when end of stream is reached. This might be when EOF is reached if the ReadStream represents a file,
or when end of request is reached if it's an HTTP request, or when the connection is closed if it's a TCP socket.

=== WriteStream

`WriteStream` is implemented by `link:../../jsdoc/http_client_request-HttpClientRequest.html[HttpClientRequest]`, `link:../../jsdoc/http_server_response-HttpServerResponse.html[HttpServerResponse]`
`link:../../jsdoc/web_socket-WebSocket.html[WebSocket]`, `link:../../jsdoc/net_socket-NetSocket.html[NetSocket]`, `link:../../jsdoc/async_file-AsyncFile.html[AsyncFile]`,
`link:../../jsdoc/packet_writestream-PacketWritestream.html[PacketWritestream]` and `link:../../jsdoc/message_producer-MessageProducer.html[MessageProducer]`

Functions:

- `link:../../jsdoc/write_stream-WriteStream.html#write[write]`:
write an object to the WriteStream. This method will never block. Writes are queued internally and asynchronously
written to the underlying resource.
- `link:../../jsdoc/write_stream-WriteStream.html#setWriteQueueMaxSize[setWriteQueueMaxSize]`:
set the number of object at which the write queue is considered _full_, and the method `link:../../jsdoc/write_stream-WriteStream.html#writeQueueFull[writeQueueFull]`
returns `true`. Note that, when the write queue is considered full, if write is called the data will still be accepted
and queued. The actual number depends on the stream implementation, for `link:../../jsdoc/buffer-Buffer.html[Buffer]` the size
represents the actual number of bytes written and not the number of buffers.
- `link:../../jsdoc/write_stream-WriteStream.html#writeQueueFull[writeQueueFull]`:
returns `true` if the write queue is considered full.
- `link:../../jsdoc/write_stream-WriteStream.html#exceptionHandler[exceptionHandler]`:
Will be called if an exception occurs on the `WriteStream`.
- `link:../../jsdoc/write_stream-WriteStream.html#drainHandler[drainHandler]`:
The handler will be called if the `WriteStream` is considered no longer full.

=== Pump

Instances of Pump have the following methods:

- `link:../../jsdoc/pump-Pump.html#start[start]`:
Start the pump.
- `link:../../jsdoc/pump-Pump.html#stop[stop]`:
Stops the pump. When the pump starts it is in stopped mode.
- `link:../../jsdoc/pump-Pump.html#setWriteQueueMaxSize[setWriteQueueMaxSize]`:
This has the same meaning as `link:../../jsdoc/write_stream-WriteStream.html#setWriteQueueMaxSize[setWriteQueueMaxSize]` on the `WriteStream`.

A pump can be started and stopped multiple times.

When a pump is first created it is _not_ started. You need to call the `start()` method to start it.