multipartkit/stream

Parse and encode multipart bodies a chunk at a time, for bodies too large to hold in memory.

A part’s headers are read whole, but its body is handed out as a Yielder of chunks of up to 64 KiB.

Types

One part of a streamed multipart body.

Get one from parse or from_part. The body can be read only once.

pub opaque type StreamPart

Values

pub fn body(
  part: StreamPart,
) -> yielder.Yielder(
  Result(BitArray, multipartkit.MultipartError),
)

Returns the part’s body as chunks of up to 64 KiB. An empty body is one empty chunk.

The yielder can be run once. A read error, such as PartTooLarge, comes out as an Error item and ends it.

pub fn content_type(part: StreamPart) -> option.Option(String)

Returns the value of the part’s Content-Type header.

pub fn drain_body(
  body: yielder.Yielder(
    Result(BitArray, multipartkit.MultipartError),
  ),
) -> Result(BitArray, multipartkit.MultipartError)

Reads a body yielder to the end and joins the chunks, stopping at the first error.

Examples

stream.drain_body(stream.body(part))
// -> Ok(<<"hello">>)
pub fn encode(
  parts: yielder.Yielder(StreamPart),
  boundary: String,
) -> yielder.Yielder(
  Result(BitArray, multipartkit.MultipartError),
)

Encodes parts with the given boundary as a yielder of byte chunks.

An invalid boundary gives a single Error(InvalidBoundary(boundary)), as multipartkit.encode does. An error from a part’s body is passed on and ends the yielder.

pub fn filename(part: StreamPart) -> option.Option(String)

Returns the filename of a form-data part, as multipartkit.filename does.

pub fn from_part(part: multipartkit.Part) -> StreamPart

Turns a buffered part into a stream part, for example to pass it to encode.

pub fn headers(part: StreamPart) -> List(#(String, String))

Returns every header of the part in the order it was written.

pub fn name(part: StreamPart) -> option.Option(String)

Returns the name parameter of a form-data part, as multipartkit.name does.

pub fn parse(
  chunks: yielder.Yielder(BitArray),
  content_type: String,
  limits: multipartkit.Limits,
) -> Result(
  yielder.Yielder(Result(StreamPart, multipartkit.MultipartError)),
  multipartkit.MultipartError,
)

Parses a multipart body that arrives as chunks.

The outer Result reports a bad content_type, with the same errors as multipartkit.parse. Each item is a part or the error that stopped parsing, after which the yielder ends.

Chunks are pulled only when the next part is needed, and the limits are checked as they arrive, so a body or part that is too large fails at the chunk that crosses the limit. Up to one part is held in memory at a time. The results match multipartkit.parse however the input is split.

Examples

let assert Ok(parts) =
  stream.parse(chunks, content_type, multipartkit.default_limits)
yielder.each(parts, fn(item) {
  case item {
    Ok(part) -> save(stream.name(part), stream.body(part))
    Error(error) -> log(error)
  }
})
✨ Search Document