| 1822 | |
| 1823 | |
| 1824 | Future<Nothing> receive( |
| 1825 | network::Socket socket, |
| 1826 | std::function<Future<Response>(const Request&)>&& f, |
| 1827 | Queue<Option<Item>> pipeline) |
| 1828 | { |
| 1829 | // Get the peer address to augment any requests we receive. |
| 1830 | Try<network::Address> address = socket.peer(); |
| 1831 | |
| 1832 | if (address.isError()) { |
| 1833 | return Failure("Failed to get peer address: " + address.error()); |
| 1834 | } |
| 1835 | |
| 1836 | const size_t size = io::BUFFERED_READ_SIZE; |
| 1837 | char* data = new char[size]; |
| 1838 | |
| 1839 | StreamingRequestDecoder* decoder = new StreamingRequestDecoder(); |
| 1840 | |
| 1841 | return loop( |
| 1842 | [=]() { |
| 1843 | return socket.recv(data, size); |
| 1844 | }, |
| 1845 | [=](size_t length) mutable -> Future<ControlFlow<Nothing>> { |
| 1846 | if (length == 0) { |
| 1847 | return Break(); |
| 1848 | } |
| 1849 | |
| 1850 | // Decode as much of the data as possible into HTTP requests. |
| 1851 | const deque<Request*> requests = decoder->decode(data, length); |
| 1852 | |
| 1853 | // NOTE: it's possible the decoder has failed but some |
| 1854 | // requests might be available, i.e., `requests.empty()` is |
| 1855 | // not true, so we wait to return a `Failure` until when there |
| 1856 | // are no requests. |
| 1857 | |
| 1858 | if (decoder->failed() && requests.empty()) { |
| 1859 | return Failure("Decoder error while receiving"); |
| 1860 | } |
| 1861 | |
| 1862 | foreach (Request* request, requests) { |
| 1863 | request->client = address.get(); |
| 1864 | // TODO(benh): To support HTTP pipelining we invoke `f` |
| 1865 | // regardless of whether the previous response has been |
| 1866 | // completed. This can make handling of requests more |
| 1867 | // difficult so we could consider supporting disabling HTTP |
| 1868 | // pipelining via some sort of "options" initially passed |
| 1869 | // in. |
| 1870 | pipeline.put(Item{request, f(*request)}); |
| 1871 | } |
| 1872 | |
| 1873 | return Continue(); // Keep looping! |
| 1874 | }) |
| 1875 | .onAny([=]() { |
| 1876 | delete decoder; |
| 1877 | delete[] data; |
| 1878 | }); |
| 1879 | } |
| 1880 | |
| 1881 | |