# Files and Streams

> Handlers run on the polling thread, so a reply or a pull that finishes later runs in a deferred slot the caller keeps, which the polling thread finishes as it keeps polling.

`#include <ucall/server.hpp>` 1.0.0-rc.1 · b7577426

Handlers run on the polling thread, so a reply or a pull that finishes later runs in a `deferred` slot the caller keeps, which the polling thread finishes as it keeps polling. Await it on the polling thread through a scheduler, or wait on it from another thread; waiting on the polling thread itself never ends. A verb taking a slot answers a refusal at once, or success while the call runs, and the slot reports the final status. A slot is reused for the next call, waiting first only if its previous call still runs, so a server keeps a ring of slots rather than one per request.

| Verb | Returns | Final when |
| - | - | - |
| `reply_parts(status, headers, parts, into)` | `status_t` | every part is sent |
| `reply_stream(status, headers)` | `expected<reply_stream_t>` | `end()` answers a `deferred<>` |
| `body_chunk(into)` | `status_t` | the next bytes arrived |

A scheduler is any type with `post(void (*poll)(void*) noexcept, void* state)`, which runs `poll(state)` later on its own loop and stores those two words, so awaiting allocates nothing in the binding.

### Serving a File

Reply with a file beneath a served directory, which the event loop opens and sends, while a coroutine awaits the send:

```cpp
task_t send_video(uc::request_t request, loop_t& loop) {
    auto [name, name_status] = request.path_parameter("name");
    ucall_reply_part_t const parts[] {uc::path_part({.directory_index = 0, .relative_path = uc::bytes_view(name)})};
    uc::deferred<> sent;
    if (std::move(request).reply_parts(ucall_http_status_ok_k, {}, parts, sent).failed()) co_return;
    uc::status_t const sent_status = co_await sent.wait(loop); // or: sent.wait()
}

ucall_bytes_view_t const directories[] {uc::bytes_view("/srv/videos")};
uc::interface_t const interfaces[] {{.address = "0.0.0.0:8080", .reply_directories = directories}};
auto [server, server_status] = uc::server_t::make(interfaces);
auto serve = [&loop](uc::request_t request) noexcept { send_video(std::move(request), loop); };
uc::status_t const routed = server.get("/videos/{name}", serve); // the caller keeps `serve` until the server is destroyed
for (;;) {
    uc::status_t const polled = server.take_call(0, std::chrono::milliseconds(1));
    if (polled == uc::status_code_t::connection_closed_k) break;
    loop.run();
}
```

`reply_parts` concatenates `bytes_part`, `path_part` and `file_part` parts into one body whose Content-Length is measured from the files. A path part resolves beneath the interface’s `reply_directories`, refusing absolute paths, `..` and links leading out, and a file part names the caller’s unbuffered descriptor until the reply is final, while bytes and paths are copied before the call returns. A missing, unreadable or too short file replaces the reply with 404, 416 or 500 before its head leaves, and the awaited status reports the cause. `deferred::status` polls, `deferred::wait()` blocks, `co_await deferred.wait(loop)` re-polls through the loop between other tasks, and a `deferred` waits as it is destroyed, so the coroutine frame, the stack or the ring holding it must outlive the call.

### Streaming a Reply

Send a reply of unknown length row by row, as a chunked stream:

```cpp
uc::status_t send_rows(uc::request_t request, std::span<std::string_view const> rows) noexcept {
    ucall_bytes_view_t const headers[] {uc::bytes_view("content-type: text/csv")};
    auto [stream, stream_status] = std::move(request).reply_stream(ucall_http_status_ok_k, headers);
    if (stream_status.failed()) return stream_status;
    for (std::string_view row : rows) {
        ucall_reply_part_t const parts[] {uc::bytes_part(row)};
        if (uc::status_t const appended = stream.append(parts); appended.failed()) return appended;
    }
    return std::move(stream).end().wait();
}
```

The stream is chunked unless a Content-Length header declares the length, `append` refuses with `status_code_t::would_block_k`, queueing nothing, while the peer lags behind, and destroying an unended stream ends it.

### Streaming an Upload

Take a large upload chunk by chunk as it arrives, rather than buffered whole, here only counting its bytes:

```cpp
task_t store(uc::request_t request, loop_t& loop) {
    std::size_t received_bytes = 0;
    uc::deferred<std::string_view> pulled;
    for (;;) {
        if (request.body_chunk(pulled).failed()) break;
        auto [chunk, chunk_status] = co_await pulled.wait(loop); // or: pulled.wait()
        if (chunk_status.failed() || chunk.empty()) break;
        received_bytes += chunk.size();
    }
    std::array<char, 24> total {};
    int const length = std::snprintf(total.data(), total.size(), "%zu", received_bytes);
    ucall_reply_part_t const parts[] {uc::bytes_part({total.data(), std::size_t(length)})};
    uc::deferred<> sent;
    if (std::move(request).reply_parts(ucall_http_status_ok_k, {}, parts, sent).failed()) co_return;
    uc::status_t const replied = co_await sent.wait(loop);
}
```

A route registered with `ucall_body_delivery_streamed_k` runs its handler once the headers arrive, and each `body_chunk` takes the bytes decoded since the last pull, valid until the next one. A pull from another thread blocks in `wait()` until the bytes arrive; on the polling thread a pull with nothing decoded answers `status_code_t::would_block_k` instead, as nothing arrives while it runs.

## API

### Types

#### `reply_stream_t`

A reply whose head left and whose body is appended part by part until `end`; destroying it ends it and waits for its file parts to send.

[server.hpp:87 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/cpp/ucall/server.hpp#L87)

```cpp
class reply_stream_t
```

### Functions

#### `memory_part`

A reply part of bytes the caller keeps unchanged until the reply is final, sent in place.

[server.hpp:69 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/cpp/ucall/server.hpp#L69)

```cpp
ucall_reply_part_t memory_part(std::string_view bytes) noexcept;
```

#### `file_part`

A reply part of a range of the caller's unbuffered descriptor, open until the reply is final.

[server.hpp:74 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/cpp/ucall/server.hpp#L74)

```cpp
ucall_reply_part_t file_part(ucall_file_range_t range) noexcept;
```

#### `path_part`

A reply part of a range of a file beneath one of the interface's reply directories.

[server.hpp:79 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/cpp/ucall/server.hpp#L79)

```cpp
ucall_reply_part_t path_part(ucall_path_range_t range) noexcept;
```
