# Files and Streams

> Handlers run on the polling goroutine, so a reply or a pull that finishes later runs on a worker: Request.Detach hands the request over as a *DetachedRequest, which reads and replies like a Request and alone has the verbs below.

`import "github.com/unum-cloud/ucall"` 1.0.0-rc.1 · b7577426

Handlers run on the polling goroutine, so a reply or a pull that finishes later runs on a worker: `Request.Detach` hands the request over as a `*DetachedRequest`, which reads and replies like a `Request` and alone has the verbs below.

| Verb | Returns | Final when |
| - | - | - |
| `ReplyParts(status, headers, parts)` | `*Deferred[struct{}]` | every part is sent |
| `ReplyStream(status, headers)` | `*ReplyStream` with `Append` and `End` | `End` answers a `*Deferred` |
| `BodyChunk()` | `*Deferred[BodyChunk]` | the next bytes arrived |

### Serving a File

Reply with a file beneath a served directory from a worker goroutine, while the event loop opens and sends it:

```go
handed := make(chan *ucall.DetachedRequest, 16)
videos := ucall.NewInterface("0.0.0.0:8080")
videos.ReplyDirectories = []string{"/srv/videos"}
server, err := ucall.NewServer([]ucall.Interface{videos}, nil)
if err != nil {
	return err
}
err = server.Get("/videos/{name}", func(request *ucall.Request) { handed <- request.Detach() })
go server.TakeCalls(0)
for detached := range handed {
	name, _ := detached.PathParameter("name")
	parts := []ucall.ReplyPart{ucall.PathPart(ucall.PathRange{Directory: 0, Path: string(name)})}
	if sent, err := detached.ReplyParts(ucall.HTTPStatusOK, nil, parts); err == nil {
		_, _ = sent.Wait()
	}
}
```

`ReplyParts` concatenates `BytesPart`, `MemoryPart`, `PathPart` and `FilePart` parts into one body whose Content-Length is measured from the files. A path part resolves beneath the interface’s `ReplyDirectories`, 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 memory part is sent in place, so its bytes stay pinned and unchanged until the reply is final, and a stream holding one must reach `End` or `Close`. A missing, unreadable or too short file replaces the reply with 404, 416 or 500 before its head leaves, and the `Deferred` reports the cause. `Deferred.Status` polls, `Deferred.Wait` parks the goroutine in the library until the call is final, `Deferred.Close` waits and drops it, and a `Deferred` dropped without either is released by the collector once final. A refusal comes back as the error beside a nil `Deferred`, before anything is submitted.

### Streaming a Reply

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

```go
func sendRows(detached *ucall.DetachedRequest, rows []string) error {
	stream, err := detached.ReplyStream(ucall.HTTPStatusOK, []string{"content-type: text/csv"})
	if err != nil {
		return err
	}
	for _, row := range rows {
		if err := stream.Append([]ucall.ReplyPart{ucall.BytesPart([]byte(row))}); err != nil {
			return err
		}
	}
	ended, err := stream.End()
	if err != nil {
		return err
	}
	_, err = ended.Wait()
	return err
}
```

The stream is chunked unless a Content-Length header declares the length, `Append` refuses with `StatusWouldBlock`, queueing nothing, while the peer lags behind, and `ReplyStream.Close` ends a stream not yet ended.

### Streaming an Upload

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

```go
func store(detached *ucall.DetachedRequest) error {
	receivedBytes := 0
	for {
		pulled, err := detached.BodyChunk()
		if err != nil {
			return err
		}
		chunk, err := pulled.Wait()
		if err != nil {
			return err
		}
		if len(chunk.Bytes()) == 0 {
			break
		}
		receivedBytes += len(chunk.Bytes())
	}
	return detached.Reply(ucall.HTTPStatusOK, nil, []byte(strconv.Itoa(receivedBytes)))
}
```

A route registered through `Server.RouteWith` with `BodyStreamed` runs its handler once the headers arrive and hands `request.Detach()` to a worker, whose pulls wait for the next bytes, each valid until the next pull. On the polling goroutine a pull with nothing decoded fails with `StatusWouldBlock` instead, as nothing arrives while it runs.

## API

### Types

#### `FileRange`

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

[server.go:749 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L749)

```go
type FileRange struct {
    Descriptor int
    Offset     uint64
    Length uint64
}
```

#### Fields

| `Length` | `uint64` | Length is the range's byte count; zero sends through the end of the file. |
| - | - | - |

#### `PathRange`

PathRange is a range of a file beneath one of the interface's reply directories.

[server.go:762 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L762)

```go
type PathRange struct {
    Directory uint
    Path      string
    Offset    uint64
    Length uint64
}
```

#### Fields

| `Length` | `uint64` | Length is the range's byte count; zero sends through the end of the file. |
| - | - | - |

#### Struct `ReplyStream`

ReplyStream is a reply whose head left and whose body is appended part by part until End.3

[server.go:859 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L859)

```go
type ReplyStream struct {
    // contains filtered or unexported fields
}
```

##### `Append`

Append queues parts on the body together, or none of them, failing with StatusWouldBlock while the peer lags behind the parts already queued.

[server.go:866 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L866)

```go
func (stream *ReplyStream) Append(parts []ReplyPart) error
```

##### `Close`

Close ends a stream not yet ended and waits for its file parts.

[server.go:890 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L890)

```go
func (stream *ReplyStream) Close() error
```

It is idempotent.

##### `End`

End ends the body, final once its file parts are sent.

[server.go:879 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L879)

```go
func (stream *ReplyStream) End() (*Deferred[struct{}], error)
```
