bindResponseStream method
Binds this scope to a streaming response, capturing chunks up to collector.maxBodyBytes,
applying simulation delays if enabled, and automatically settling with complete or fail.
Implementation
Stream<List<int>> bindResponseStream(
Stream<List<int>> responseStream, {
required int statusCode,
Map<String, String>? headers,
String? contentType,
}) {
if (!isActive) return responseStream;
return teeStreamCapture(
responseStream,
maxBytes: collector.maxBodyBytes,
chunkDelay: collector.delayForChunk,
onDone: (captured, totalBytes) {
final isTruncated =
collector.maxBodyBytes > 0 && totalBytes > collector.maxBodyBytes;
final elapsed = _context != null
? DateTime.now().difference(_context!.startedAt).inMilliseconds
: null;
unawaited(
complete(
statusCode: statusCode,
headers: headers,
bodyBytes: captured,
responseSizeBytes: totalBytes,
contentType: contentType,
durationMs: elapsed,
responseTruncatedAtStorage: isTruncated,
),
);
},
onError: (error, st, captured, totalBytes) {
final isTruncated =
collector.maxBodyBytes > 0 && totalBytes > collector.maxBodyBytes;
fail(
error,
stackTrace: st,
statusCode: statusCode,
responseHeaders: headers,
responseBodyBytes: captured,
responseSizeBytes: totalBytes,
responseTruncatedAtStorage: isTruncated,
);
},
onCancel: (captured, totalBytes) {
final isTruncated =
collector.maxBodyBytes > 0 && totalBytes > collector.maxBodyBytes;
fail(
'CancellationException',
errorType: 'CancellationException',
errorMessage: 'Stream subscription was canceled by client.',
statusCode: statusCode,
responseHeaders: headers,
responseBodyBytes: captured,
responseSizeBytes: totalBytes,
responseTruncatedAtStorage: isTruncated,
);
},
);
}