Skip to content

Added cache control for http request within BrowserClient #1706

New issue

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

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

Already on GitHub? Sign in to your account

Open
wants to merge 40 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
9ba5471
Update README.md
seifibrahim32 Mar 13, 2024
ee01325
Merge branch 'dart-lang:master' into master
seifibrahim32 Jan 31, 2025
3a26def
Added caching options for http package
seifibrahim32 Feb 2, 2025
3ba65df
Enabled lints
seifibrahim32 Feb 2, 2025
f5c9c11
Fixed CI errors
seifibrahim32 Feb 2, 2025
52ff2c5
Changed from HttpCacheUtils to HttpCacheOptions
seifibrahim32 Feb 2, 2025
7f70434
Reverted readme file
seifibrahim32 Feb 3, 2025
ae7be97
Reverted to last commits for request files
seifibrahim32 Feb 3, 2025
1ca0c3a
Reformated the committed files
seifibrahim32 Feb 3, 2025
7a5c30d
Changed values
seifibrahim32 Feb 3, 2025
85daade
Passing CI stages
seifibrahim32 Feb 3, 2025
7ece5aa
Changed the parameter to String type
seifibrahim32 Feb 4, 2025
4bca978
Reverted utils.dart
seifibrahim32 Feb 5, 2025
dad889c
Changed CacheMode from utils to browser_client file
seifibrahim32 Feb 5, 2025
2889cb2
Enhanced BrowserClient class
seifibrahim32 Feb 5, 2025
3d17957
Formatted for CI passover
seifibrahim32 Feb 5, 2025
a1f47db
Export CacheMode
seifibrahim32 Feb 6, 2025
cab59fc
Added some cache tests
seifibrahim32 Feb 11, 2025
5831578
Reverted utils.dart
seifibrahim32 Feb 11, 2025
2fd11c1
Reverted stub server
seifibrahim32 Feb 11, 2025
53dc82f
Add tests cache including fixing CI passover
seifibrahim32 Feb 12, 2025
1adce3e
Updated the branch fork
seifibrahim32 Feb 16, 2025
7d50328
Update browser_client with formatted style
seifibrahim32 Feb 16, 2025
410d227
Added for tests branch
seifibrahim32 Feb 19, 2025
83672f8
Added browser clients tests including test fixes
seifibrahim32 Mar 10, 2025
40609bc
Updated pubspec.yaml file
seifibrahim32 Mar 10, 2025
ff7f7e8
Reset the server port to zero
seifibrahim32 Mar 10, 2025
a63d6ce
Fix the dart.yml
seifibrahim32 Mar 10, 2025
7e1bc9f
Fixed WASM runtime
seifibrahim32 Mar 10, 2025
0eabc8d
Fixed WASM runtime v2
seifibrahim32 Mar 10, 2025
c144307
Fixed WASM runtime v4
seifibrahim32 Mar 10, 2025
34a87fb
Fixed WASM runtime v5
seifibrahim32 Mar 10, 2025
5294e96
Fixed WASM runtime v5
seifibrahim32 Mar 10, 2025
d12c0a4
Update CHANGELOG.md
seifibrahim32 Mar 10, 2025
3c53220
Update pubspec.yaml
seifibrahim32 Mar 10, 2025
b485213
Update CHANGELOG.md
seifibrahim32 Mar 10, 2025
f65dd4f
Update cache_test.dart
seifibrahim32 Mar 10, 2025
42251ea
Changed POST to GET and ensured of some tests
seifibrahim32 Mar 10, 2025
4c7471f
Added etags and cache control
seifibrahim32 Mar 11, 2025
4896114
Fixed conflicts
seifibrahim32 Mar 12, 2025
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
3 changes: 2 additions & 1 deletion pkgs/http/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
to use utf8 instead of latin1, ensuring proper JSON decoding.
* Avoid references to `window` in `BrowserClient`, restoring support for web
workers and NodeJS.

* Added caching options for `BrowserClient`.

## 1.3.0

* Fixed unintended HTML tags in doc comments.
Expand Down
2 changes: 1 addition & 1 deletion pkgs/http/lib/browser_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

export 'src/browser_client.dart' show BrowserClient;
export 'src/browser_client.dart' show BrowserClient, CacheMode;
33 changes: 32 additions & 1 deletion pkgs/http/lib/src/browser_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

import 'dart:async';
import 'dart:js_interop';

import 'package:web/web.dart'
show
AbortController,
Expand All @@ -30,6 +29,23 @@ BaseClient createClient() {
return BrowserClient();
}

/// Caching mode used by the [BrowserClient].
///
/// Sets the request cache value of the browser Fetch API.
/// [`Request.cache`](https://developer.mozilla.org/en-US/docs/Web/API/Request/cache) property.
enum CacheMode {
defaultType('default'),
reload('reload'),
noStore('no-store'),
noCache('no-cache'),
forceCache('force-cache'),
onlyIfCached('only-if-cached');

final String cacheType;

const CacheMode(this.cacheType);
}

@JS('fetch')
external JSPromise<Response> _fetch(
RequestInfo input, [
Expand All @@ -51,6 +67,20 @@ external JSPromise<Response> _fetch(
class BrowserClient extends BaseClient {
final _abortController = AbortController();

final CacheMode _cacheMode;

/// Create a new browser-based HTTP Client.
///
/// If [cacheMode] is provided then it can be used to cache the request
/// in the browser.
///
/// For example:
/// ```dart
/// final client = BrowserClient(cacheMode: CacheMode.reload);
/// ```
BrowserClient({CacheMode cacheMode = CacheMode.defaultType})
: _cacheMode = cacheMode;

/// Whether to send credentials such as cookies or authorization headers for
/// cross-site requests.
///
Expand All @@ -74,6 +104,7 @@ class BrowserClient extends BaseClient {
RequestInit(
method: request.method,
body: bodyBytes.isNotEmpty ? bodyBytes.toJS : null,
cache: _cacheMode.cacheType,
credentials: withCredentials ? 'include' : 'same-origin',
headers: {
if (request.contentLength case final contentLength?)
Expand Down
83 changes: 83 additions & 0 deletions pkgs/http/test/html/cache_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
// Copyright (c) 2025, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

@TestOn('browser')
library;

import 'dart:async';

import 'package:http/browser_client.dart';
import 'package:http/http.dart' as http;
import 'package:http/http.dart';
import 'package:test/test.dart';

import 'utils.dart';

void main() {
late Uri url;
setUp(() async {
final channel = spawnHybridUri(Uri(path: '/test/stub_server.dart'));
var port = (await channel.stream.first as num).toInt();
url = echoUrl.replace(port: port);
});

test('#send a GET with default type', () async {
var client = BrowserClient(cacheMode: CacheMode.defaultType);
Copy link
Collaborator

Choose a reason for hiding this comment

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

You are only doing a single request here so I'm not sure how this is testing the caching behavior.

Copy link
Author

@seifibrahim32 seifibrahim32 Mar 14, 2025

Choose a reason for hiding this comment

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

Nope, it is two GET requests, when it is set to default type it is cached once.

Copy link
Author

Choose a reason for hiding this comment

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

I guess, I need to drain the request so, I can see the difference.

await client.get(url);
var response = await client.get(url);
client.close();

expect(response.statusCode, 200);
expect(response.reasonPhrase, 'OK');
expect(response.body, parse(allOf(containsPair('numOfRequests', 1))));
});

test('#send a GET Request with reload type', () async {
var client = BrowserClient(cacheMode: CacheMode.reload);
await client.get(url);
var response = await client.get(url);
expect(response.body, parse(allOf(containsPair('numOfRequests', 2))));
client.close();
});

test('#send a GET with no-cache type', () async {
var client = BrowserClient(cacheMode: CacheMode.noCache);

await client.get(url);
var response = await client.get(url);
client.close();
expect(
response.body,
parse(anyOf(containsPair('numOfRequests', 2),
Copy link
Collaborator

Choose a reason for hiding this comment

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

Shouldn't numOfRequests always be 2?

Copy link
Author

Choose a reason for hiding this comment

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

Yes, see most of other tests.

Copy link
Author

Choose a reason for hiding this comment

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

Do you have other suggestions regarding the tests? @brianquinlan

containsPair('cache-control', ['max-age=0']))));
});

test('#send a GET with no-store type', () async {
var client = BrowserClient(cacheMode: CacheMode.noStore);

await client.get(url);
var response = await client.get(url);
client.close();
expect(response.body, parse(allOf(containsPair('numOfRequests', 2))));
});

test('#send a GET with force-store type', () async {
var client = BrowserClient(cacheMode: CacheMode.forceCache);

await client.get(url);
var response = await client.get(url);
client.close();
expect(response.body, parse(allOf(containsPair('numOfRequests', 1))));
});

test('#send a StreamedRequest with only-if-cached type', () {
var client = BrowserClient(cacheMode: CacheMode.onlyIfCached);
var request = http.StreamedRequest('GET', url);

expectLater(client.send(request), throwsA(isA<ClientException>()));
unawaited(request.sink.close());

client.close();
});
}
16 changes: 13 additions & 3 deletions pkgs/http/test/html/client_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,30 @@ import 'package:test/test.dart';
import 'utils.dart';

void main() {
late int port;
setUpAll(() async {
final channel =
spawnHybridUri(Uri(path: '/test/stub_server.dart'), stayAlive: true);
port = (await channel.stream.first as num).toInt();
});

test('#send a StreamedRequest', () async {
var client = BrowserClient();
var request = http.StreamedRequest('POST', echoUrl);
var request = http.StreamedRequest('POST', echoUrl.replace(port: port));

var responseFuture = client.send(request);
request.sink.add('{"hello": "world"}'.codeUnits);
unawaited(request.sink.close());

var response = await responseFuture;

var bytesString = await response.stream.bytesToString();

client.close();

expect(bytesString, equals('{"hello": "world"}'));
}, skip: 'Need to fix server tests for browser');
expect(bytesString,
parse(allOf(containsPair('body', '{"hello": "world"}'.codeUnits))));
});

test('#send with an invalid URL', () {
var client = BrowserClient();
Expand Down
22 changes: 15 additions & 7 deletions pkgs/http/test/html/streamed_request_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,27 +14,35 @@ import 'package:test/test.dart';
import 'utils.dart';

void main() {
late Uri url;
setUpAll(() async {
final channel =
spawnHybridUri(Uri(path: '/test/stub_server.dart'), stayAlive: true);
var port = (await channel.stream.first as num).toInt();
url = echoUrl.replace(port: port);
});
group('contentLength', () {
test("works when it's set", () async {
var request = http.StreamedRequest('POST', echoUrl)
var request = http.StreamedRequest('POST', url)
..contentLength = 10
..sink.add([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
unawaited(request.sink.close());

final response = await BrowserClient().send(request);

expect(await response.stream.toBytes(),
equals([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));
expect(await response.stream.bytesToString(),
parse(allOf(containsPair('body', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))));
});

test("works when it's not set", () async {
var request = http.StreamedRequest('POST', echoUrl);
var request = http.StreamedRequest('POST', url);
request.sink.add([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
unawaited(request.sink.close());

final response = await BrowserClient().send(request);
expect(await response.stream.toBytes(),
equals([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));

expect(await response.stream.bytesToString(),
parse(allOf(containsPair('body', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))));
});
}, skip: 'Need to fix server tests for browser');
});
}
14 changes: 14 additions & 0 deletions pkgs/http/test/stub_server.dart
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,15 @@ import 'package:http/src/utils.dart';
import 'package:stream_channel/stream_channel.dart';

void hybridMain(StreamChannel<dynamic> channel) async {
var numOfRequests = 0;
final server = await HttpServer.bind('localhost', 0);
final url = Uri.http('localhost:${server.port}', '');
server.listen((request) async {
var path = request.uri.path;
var response = request.response;
response.headers
..set('Cache-Control', 'public, max-age=30, immutable')
..set('etag', '312424');

if (path == '/error') {
response
Expand Down Expand Up @@ -53,6 +57,15 @@ void hybridMain(StreamChannel<dynamic> channel) async {
return;
}

// For browser runtime testing...
if (path == '/echo') {
++numOfRequests;

response
..headers.add('Access-Control-Allow-Origin', '*')
..headers.add('Access-Control-Allow-Methods', 'POST, GET');
}

var requestBodyBytes = await ByteStream(request).toBytes();
var encodingName = request.uri.queryParameters['response-encoding'];
var outputEncoding =
Expand Down Expand Up @@ -88,6 +101,7 @@ void hybridMain(StreamChannel<dynamic> channel) async {
'path': request.uri.path,
if (requestBody != null) 'body': requestBody,
'headers': headers,
if (path == '/echo') 'numOfRequests': numOfRequests
};

var body = json.encode(content);
Expand Down
Loading