StreamingResponseBody とバイトストリーム

StreamingResponseBody は、ハンドラーが少しずつ書き、その間にクライアントが最初の部分をもう受け取っているボディです。Stream<Uint8List> または Stream<List<int>> を返すと宣言したメソッドは、バイトのチャンクのストリームで同じことを行います。

使う理由

大きいボディや作るのに時間がかかるボディがあります。全注文の CSV エクスポート、バックアップ、その場で作る ZIP、プロセスの出力などです。先に全体を作ると、メモリを消費し、クライアントは最初のバイトまで待たされます。作られたそばから書けば:

コードがボディを一歩ずつ (行、テキスト、バイト) 書くときは StreamingResponseBody を使います。すでにバイトストリーム (ファイルの openRead()、Process.stdout、Feign クライアントのストリーミングされたレスポンス) があるときは Stream<Uint8List> を返します。ディスク上のファイルには Resource のほうが簡単で、範囲とキャッシュも加わります。一連のメッセージには サーバー送信イベント を使ってください。

例

import 'dart:io';
import 'dart:typed_data';

import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';

class Book {
  const Book({required this.isbn, required this.title});

  final String isbn;
  final String title;
}

@Service()
class Books {
  Stream<Book> all() => Stream.fromIterable(const [
    Book(isbn: '9780441013593', title: 'Dune'),
    Book(isbn: '9780553293357', title: 'Foundation'),
  ]);
}

@RestController()
@RequestMapping('/api')
class ExportController {
  ExportController(this.books);

  final Books books;

  // 一行ずつ書き、全体をメモリに持つことのない CSV エクスポート。
  @GetMapping.of(path: '/books.csv', produces: 'text/csv')
  StreamingResponseBody export() => StreamingResponseBody((out) async {
    out.write('isbn,title\n');
    await for (final book in books.all()) {
      out.write('${book.isbn},${book.title}\n');
      // 書いたものを送り、出ていくまで待つ。
      await out.flush();
    }
  });

  // 同じものを、ファイル名付きのダウンロードとして。
  @GetMapping('/books-download.csv')
  ResponseEntity<StreamingResponseBody> download() =>
      ResponseEntity.status(HttpStatus.ok)
          .contentType('text/csv; charset=utf-8')
          .header(HttpHeaders.contentDispositionHeader, [
            '${const ContentDisposition.attachment(filename: 'books.csv')}',
          ])
          .body(export());

  // ストリームからの生のバイト: `produces` で別の指定がなければ
  // application/octet-stream。
  @GetMapping.of(path: '/backup', produces: 'application/gzip')
  Stream<Uint8List> backup() => File('/var/shop/backup.tar.gz')
      .openRead()
      .map(Uint8List.fromList);

  // ボディの中に別のストリームを加える。
  @GetMapping('/bundle')
  StreamingResponseBody bundle() => StreamingResponseBody((out) async {
    out.add(Uint8List.fromList([0x50, 0x4b]));
    await out.addStream(File('/var/shop/rest.bin').openRead());
  });
}

StreamingResponseBody

メンバー 型 意味
StreamingResponseBody(writeTo) コンストラクター writeTo が書くボディ。
writeTo Future<void> Function(ResponseBodySink out) out にボディを書く。その Future が完了するとレスポンスが終わる。

ResponseBodySink

メンバー 意味
add(List<int> bytes) ボディにバイトを加える。
write(String text) UTF-8 でエンコードしたテキストを加える。
Future<void> flush() それまでに書いたものをクライアントに送る。さらに書く前に await する。
Future<void> addStream(Stream<List<int>> stream) stream のすべてのチャンクを加える。ストリームが終わると完了する。

書いたものはバッファーに入ります。flush しなければ、バッファーが埋まるかボディが終わるまで、クライアントは何も受け取らないかもしれません。クライアントに進行状況を見せたいときは、論理的なまとまり (行、レコード) ごとに flush を呼び、それを await してください。そうすることで、遅いクライアントがあなたのループの速度を落とします。

バイトストリーム

宣言した戻り値の型 書き出し方
Stream<Uint8List> 生のバイト。各チャンクを届いたとおりに。
Stream<List<int>> 生のバイト。各チャンクを届いたとおりに。
その他の Stream<T> バイトではなく サーバー送信イベント。
ResponseEntity<Stream<Uint8List>> エンティティのステータスとヘッダー付きの生のバイト。

レスポンス

エラー

Spring (Java) との対応

@GetMapping(path = "/api/books.csv", produces = "text/csv")
StreamingResponseBody export() {
  return out -> {
    for (Book book : books.all()) {
      out.write((book.isbn() + "," + book.title() + "\n").getBytes(UTF_8));
      out.flush();
    }
  };
}

重要な違い:

関連項目