diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 09fc04c74..11e855c65 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -213,6 +213,11 @@ jobs:
working-directory: packages/${{ matrix.package.name }}
run: dart test -p chrome test/browser
+ - name: Run web tests
+ if: ${{ matrix.package.name == 'yet_another_json_isolate' }}
+ working-directory: packages/${{ matrix.package.name }}
+ run: dart test -p chrome
+
- name: Upload coverage to Coveralls
if: ${{ matrix.channel == 'stable' }}
uses: coverallsapp/github-action@8d6379e14d29928660c4ba802d8e85393440b329 # v2.3.8
diff --git a/MIGRATION.md b/MIGRATION.md
index 289c5f959..435d28b22 100644
--- a/MIGRATION.md
+++ b/MIGRATION.md
@@ -1891,9 +1891,13 @@ current headers.
final client = SupabaseClient(url, key, isolate: YAJsonIsolate()..initialize());
// After
-final client = SupabaseClient(url, key, jsonCodec: YAJsonIsolate()..initialize());
+final client = SupabaseClient(url, key, jsonCodec: YAJsonIsolate());
```
+`YAJsonIsolate.initialize()` is removed, because there is nothing to initialize, so delete the
+call. On web, `YAJsonIsolate` is no longer `const`, and using it after `dispose()` throws a
+`StateError` as it already did on other platforms.
+
Implement `AsyncJsonCodec` to encode and decode JSON your own way. `YAJsonIsolate` is not exported
by `supabase` or `supabase_flutter`, so depend on `yet_another_json_isolate` directly to name it.
diff --git a/packages/postgrest/lib/src/postgrest.dart b/packages/postgrest/lib/src/postgrest.dart
index 011a612ce..25d447f42 100644
--- a/packages/postgrest/lib/src/postgrest.dart
+++ b/packages/postgrest/lib/src/postgrest.dart
@@ -67,7 +67,7 @@ class PostgrestClient {
_schema = schema,
_schemaIsExplicit = false,
headers = Map.unmodifiable({...defaultHeaders, ...?headers}),
- _jsonCodec = jsonCodec ?? (YAJsonIsolate()..initialize()),
+ _jsonCodec = jsonCodec ?? YAJsonIsolate(),
_ownsJsonCodec = jsonCodec == null {
postgrestLogger.config(
() =>
diff --git a/packages/supabase/lib/src/supabase_client.dart b/packages/supabase/lib/src/supabase_client.dart
index f64779ac3..f34dddd6e 100644
--- a/packages/supabase/lib/src/supabase_client.dart
+++ b/packages/supabase/lib/src/supabase_client.dart
@@ -101,7 +101,7 @@ class SupabaseClient {
...?headers,
},
_httpClient = httpClient,
- _jsonCodec = jsonCodec ?? (YAJsonIsolate()..initialize()),
+ _jsonCodec = jsonCodec ?? YAJsonIsolate(),
_ownsJsonCodec = jsonCodec == null {
if (accessToken == null &&
authOptions.asyncStorage == null &&
diff --git a/packages/supabase/test/client_test.dart b/packages/supabase/test/client_test.dart
index 608adb8d1..fe578289f 100644
--- a/packages/supabase/test/client_test.dart
+++ b/packages/supabase/test/client_test.dart
@@ -618,7 +618,6 @@ void main() {
'does not dispose a supplied codec, so the caller keeps ownership',
() async {
final jsonCodec = YAJsonIsolate();
- await jsonCodec.initialize();
final client = SupabaseClient(
supabaseUrl,
diff --git a/packages/supabase_functions/lib/src/functions_client.dart b/packages/supabase_functions/lib/src/functions_client.dart
index fe3b5afbf..937fed0cb 100644
--- a/packages/supabase_functions/lib/src/functions_client.dart
+++ b/packages/supabase_functions/lib/src/functions_client.dart
@@ -43,7 +43,7 @@ class FunctionsClient {
),
_url = url,
_headers = {...FunctionsConstants.defaultHeaders, ...headers},
- _jsonCodec = jsonCodec ?? (YAJsonIsolate()..initialize()),
+ _jsonCodec = jsonCodec ?? YAJsonIsolate(),
_ownsJsonCodec = jsonCodec == null,
// The transport belongs to the caller, so the client never closes it,
// the same way it leaves a caller-provided JSON codec alone.
diff --git a/packages/yet_another_json_isolate/README.md b/packages/yet_another_json_isolate/README.md
index 703f1f3f6..ac71851a5 100644
--- a/packages/yet_another_json_isolate/README.md
+++ b/packages/yet_another_json_isolate/README.md
@@ -7,7 +7,7 @@
yet_another_json_isolate
- JSON parsing that never blocks the main isolate for long: small payloads are processed inline, large payloads on short lived isolates that hand their result back without copying.
+ JSON parsing that never blocks the main isolate for long: small payloads are processed inline, large payloads on short lived isolates that hand their result back without copying. On web, which has no isolates, every payload is processed inline on the main thread.
diff --git a/packages/yet_another_json_isolate/benchmark/yet_another_json_isolate_benchmark.dart b/packages/yet_another_json_isolate/benchmark/yet_another_json_isolate_benchmark.dart
index 660b16629..4451f6fc0 100644
--- a/packages/yet_another_json_isolate/benchmark/yet_another_json_isolate_benchmark.dart
+++ b/packages/yet_another_json_isolate/benchmark/yet_another_json_isolate_benchmark.dart
@@ -170,7 +170,6 @@ _Scenario _concurrentDecodeScenario(
Future<_ScenarioResult> _runScenario(_Scenario scenario) async {
final isolate = YAJsonIsolate(debugName: 'benchmark');
- await isolate.initialize();
final warmupIterations = (scenario.iterations ~/ 10).clamp(2, 20);
for (var i = 0; i < warmupIterations; i++) {
diff --git a/packages/yet_another_json_isolate/example/yet_another_json_isolate_example.dart b/packages/yet_another_json_isolate/example/yet_another_json_isolate_example.dart
index 127f07217..061580bcb 100644
--- a/packages/yet_another_json_isolate/example/yet_another_json_isolate_example.dart
+++ b/packages/yet_another_json_isolate/example/yet_another_json_isolate_example.dart
@@ -3,8 +3,6 @@ import 'package:yet_another_json_isolate/yet_another_json_isolate.dart';
void main() async {
final isolate = YAJsonIsolate();
- await isolate.initialize();
-
final json = await isolate.decode('{"a": 1, "b": 2}');
print(json);
diff --git a/packages/yet_another_json_isolate/lib/src/json_isolate_io.dart b/packages/yet_another_json_isolate/lib/src/json_isolate_io.dart
index d29e6d226..444135b0c 100644
--- a/packages/yet_another_json_isolate/lib/src/json_isolate_io.dart
+++ b/packages/yet_another_json_isolate/lib/src/json_isolate_io.dart
@@ -13,10 +13,10 @@ import 'async_json_codec.dart';
/// messaging overhead.
const _isolateThresholdBytes = 64 * 1024;
-/// Depth guard for [_remainingBudget], so that a cyclic or extremely deep
-/// structure is handed to the isolate path instead of overflowing the stack
-/// during estimation.
-const _maxEstimationDepth = 512;
+/// Depth guard for [_Conversion], so that a cyclic or extremely deep structure
+/// does not overflow the stack. Such a structure is encoded on an isolate
+/// without being converted first, so its `toJson()` methods run there.
+const _maxConversionDepth = 512;
final Converter, Object?> _utf8JsonDecoder = const Utf8Decoder().fuse(
const JsonDecoder(),
@@ -36,7 +36,6 @@ class YAJsonIsolate implements AsyncJsonCodec {
/// The debug name used for the isolates spawned by this instance.
final String? debugName;
- bool _hasStartedInitialize = false;
Future? _disposal;
final Set> _activeWork = {};
@@ -48,22 +47,6 @@ class YAJsonIsolate implements AsyncJsonCodec {
}
}
- /// Kept for backwards compatibility.
- ///
- /// There is no persistent isolate anymore, so there is nothing to
- /// initialize: large payloads are processed on short lived isolates spawned
- /// per call.
- Future initialize() {
- return Future.sync(() {
- _throwIfDisposed();
- assert(
- _hasStartedInitialize == false,
- 'initialize() can only be called once per isolate.',
- );
- _hasStartedInitialize = true;
- });
- }
-
/// Dispose the instance.
///
/// Rejects new work immediately and completes once the isolate work that
@@ -127,76 +110,144 @@ class YAJsonIsolate implements AsyncJsonCodec {
/// Encodes [json] into a JSON string, like [jsonEncode].
///
- /// Payloads estimated to be small are encoded inline, the rest on a short
- /// lived isolate. A value that cannot be sent to an isolate, for example an
- /// object whose `toJson()` result is encodable while the object itself
- /// holds a `ReceivePort`, is encoded inline instead.
+ /// Objects that are not a JSON value are first converted with their
+ /// `toJson()` method on the calling isolate, once for each place they
+ /// appear, so side effects of that method happen where the caller expects
+ /// them. Payloads estimated to be small are then encoded inline, the rest on
+ /// a short lived isolate. A value that cannot be sent to an isolate, for
+ /// example a custom `Map` that holds a `ReceivePort`, is encoded inline
+ /// instead, and so is a value that cannot be encoded, which throws the same
+ /// error as [jsonEncode].
///
/// The value is consumed before control returns to the caller, so it can
/// be mutated as soon as the call returns.
@override
Future encode(Object? json) async {
_throwIfDisposed();
- if (_remainingBudget(json, _isolateThresholdBytes, 0) >= 0) {
+ final conversion = _Conversion();
+ final converted = conversion.convert(json, 0);
+ if (identical(converted, _unencodable)) {
return jsonEncode(json);
}
+ final isTooDeep = identical(converted, _tooDeep);
+ final encodable = isTooDeep ? json : converted;
+ if (!isTooDeep && conversion.budget >= 0) {
+ return jsonEncode(encodable);
+ }
try {
- return await _runTracked(() => jsonEncode(json));
+ return await _runTracked(() => jsonEncode(encodable));
} on ArgumentError {
- return jsonEncode(json);
+ return jsonEncode(encodable);
}
}
}
-/// Returns what is left of [budget] after subtracting an estimate of the
-/// encoded size of [value], or a negative number as soon as the estimate
-/// exceeds the budget.
+/// Returned by [_Conversion.convert] for a value that [jsonEncode] rejects.
+const Object _unencodable = Object();
+
+/// Returned by [_Conversion.convert] for a structure nested deeper than
+/// [_maxConversionDepth].
+const Object _tooDeep = Object();
+
+bool _isFailure(Object? converted) =>
+ identical(converted, _unencodable) || identical(converted, _tooDeep);
+
+/// Replaces every object that is not a JSON value with the result of its
+/// `toJson()` method, the way [jsonEncode] converts it, while estimating the
+/// encoded size.
///
-/// The estimate is deliberately rough: it only has to decide whether encoding
-/// inline could block the calling isolate for too long, and it must cost far
-/// less than the encoding itself. Values of unrecognized types, and structures
-/// nested deeper than [_maxEstimationDepth], exhaust the budget immediately so
-/// they are encoded on an isolate.
+/// Lists and maps are only copied when something inside them is replaced.
///
-/// Numbers are charged at their maximum textual width. Strings are charged
-/// one character each, without inspecting them for characters that JSON
-/// escaping expands, because such a scan would cost nearly as much as the
-/// encoding itself. A string dense in escaped characters can therefore be
-/// undercounted by up to a factor of six, which at worst lets a payload a few
-/// times [_isolateThresholdBytes] be encoded inline.
-int _remainingBudget(Object? value, int budget, int depth) {
- if (budget < 0 || depth > _maxEstimationDepth) {
- return -1;
- }
- switch (value) {
- case null:
- return budget - 4;
- case bool _:
- return budget - 5;
- case num _:
- return budget - 20;
- case String string:
- return budget - string.length - 2;
- case List list:
- budget -= 2;
- for (final element in list) {
- budget = _remainingBudget(element, budget, depth + 1) - 1;
- if (budget < 0) {
- return -1;
+/// The estimate is deliberately rough: it only has to decide whether encoding
+/// inline could block the calling isolate for too long. Numbers are charged
+/// at their maximum textual width. Strings are charged one character each,
+/// without inspecting them for characters that JSON escaping expands, because
+/// such a scan would cost nearly as much as the encoding itself. A string
+/// dense in escaped characters can therefore be undercounted by up to a
+/// factor of six, which at worst lets a payload a few times
+/// [_isolateThresholdBytes] be encoded inline.
+class _Conversion {
+ /// What is left of [_isolateThresholdBytes] after the values converted so
+ /// far, negative once the estimate exceeds it.
+ int budget = _isolateThresholdBytes;
+
+ /// Returns [value] converted, or [_unencodable] or [_tooDeep] when it
+ /// cannot be.
+ Object? convert(Object? value, int depth) {
+ if (depth > _maxConversionDepth) {
+ return _tooDeep;
+ }
+ switch (value) {
+ case null:
+ budget -= 4;
+ return null;
+ case bool _:
+ budget -= 5;
+ return value;
+ case String string:
+ budget -= string.length + 2;
+ return string;
+ case num number:
+ if (!number.isFinite) {
+ return _unencodable;
}
- }
- return budget;
- case Map map:
- budget -= 2;
- for (final entry in map.entries) {
- budget = _remainingBudget(entry.key, budget, depth + 1);
- budget = _remainingBudget(entry.value, budget, depth + 1) - 2;
- if (budget < 0) {
- return -1;
+ budget -= 20;
+ return number;
+ case List list:
+ budget -= 2;
+ List