Skip to content

chore: optimize Request.read #1410

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 6 additions & 8 deletions packages/dart_frog/lib/src/request.dart
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ class Request {

Request._(this._request);

shelf.Request _request;
final shelf.Request _request;

/// Connection information for the associated HTTP request.
HttpConnectionInfo get connectionInfo {
Expand All @@ -120,16 +120,12 @@ class Request {

/// Returns a [Future] containing the body as a [String].
Future<String> body() async {
const requestBodyKey = 'dart_frog.request.body';
final bodyFromContext =
_request.context[requestBodyKey] as Completer<String>?;
if (bodyFromContext != null) return bodyFromContext.future;
final bodyFromContext = _bodyFutureExpando[_request];
if (bodyFromContext != null) return bodyFromContext;

final completer = Completer<String>();
try {
_request = _request.change(
context: {..._request.context, requestBodyKey: completer},
);
_bodyFutureExpando[_request] = completer.future;
completer.complete(await _request.readAsString());
} catch (error, stackTrace) {
completer.completeError(error, stackTrace);
Expand Down Expand Up @@ -158,3 +154,5 @@ class Request {
return Request._(_request.change(headers: headers, path: path, body: body));
}
}

final _bodyFutureExpando = Expando<Future<String>>('dart_frog.request.body');
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not that familiar with Expandos, would love to see a description on the PR to explain how this improves performance

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You all would have to measure it.

On the VM, they're pretty cheap. And now you're avoiding copying everything all the time which should be a lot cheaper