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? copy; + for (var index = 0; index < list.length; index++) { + final element = list[index]; + final converted = convert(element, depth + 1); + if (_isFailure(converted)) { + return converted; + } + budget -= 1; + if (copy == null && !identical(converted, element)) { + copy = List.of(list.take(index)); + } + copy?.add(converted); } - } - return budget; - default: - return -1; + return copy ?? list; + case Map map: + budget -= 2; + Map? copy; + var index = 0; + for (final MapEntry(:key, value: entryValue) in map.entries) { + if (key is! String) { + return _unencodable; + } + final converted = convert(entryValue, depth + 1); + if (_isFailure(converted)) { + return converted; + } + budget -= key.length + 4; + if (copy == null && !identical(converted, entryValue)) { + copy = { + for (final entry in map.entries.take(index)) + entry.key as String: entry.value, + }; + } + copy?[key] = converted; + index++; + } + return copy ?? map; + default: + final Object? json; + try { + json = (value as dynamic).toJson(); + } on Object { + return _unencodable; + } + return switch (json) { + null || + bool _ || + String _ || + num _ || + List _ || + Map _ => convert(json, depth + 1), + _ => _unencodable, + }; + } } } diff --git a/packages/yet_another_json_isolate/lib/src/json_isolate_web.dart b/packages/yet_another_json_isolate/lib/src/json_isolate_web.dart index 6f8071058..38ccc69af 100644 --- a/packages/yet_another_json_isolate/lib/src/json_isolate_web.dart +++ b/packages/yet_another_json_isolate/lib/src/json_isolate_web.dart @@ -9,36 +9,57 @@ final Converter, Object?> _utf8JsonDecoder = const Utf8Decoder().fuse( /// Web variant of [YAJsonIsolate]. /// -/// The web platform has no isolates, so all work happens inline. Decoding -/// from bytes still fuses the UTF-8 and JSON decoding steps, which avoids -/// materializing the intermediate string. +/// The web platform has no isolates, so all work happens inline on the +/// calling thread and a large payload blocks it for as long as the work +/// takes. Decoding from bytes still fuses the UTF-8 and JSON decoding steps, +/// which avoids materializing the intermediate string. class YAJsonIsolate implements AsyncJsonCodec { - /// [debugName] is accepted for API parity with the IO implementation but - /// unused, since there are no isolates on web. - const YAJsonIsolate({ - String? debugName, + /// Creates a codec. [debugName] is unused on web, where there are no + /// isolates to name. + YAJsonIsolate({ + this.debugName, }); - /// Kept for backwards compatibility; there is nothing to initialize on web. - Future initialize() => Future.value(); + /// The debug name used for the isolates spawned by this instance on other + /// platforms. + final String? debugName; + bool _isDisposed = false; + + void _throwIfDisposed() { + if (_isDisposed) { + throw StateError('This YAJsonIsolate has already been disposed.'); + } + } + + /// Dispose the instance. + /// + /// Safe to call more than once. Using the instance afterwards throws a + /// [StateError]. @override - Future dispose() => Future.value(); + Future dispose() { + _isDisposed = true; + return Future.value(); + } @override Future decode(String json) async { + _throwIfDisposed(); await null; return jsonDecode(json); } @override Future decodeBytes(Uint8List encodedJson) { - return Future.sync(() => _utf8JsonDecoder.convert(encodedJson)); + return Future.sync(() { + _throwIfDisposed(); + return _utf8JsonDecoder.convert(encodedJson); + }); } @override Future encode(Object? json) async { - await null; + _throwIfDisposed(); return jsonEncode(json); } } diff --git a/packages/yet_another_json_isolate/lib/yet_another_json_isolate.dart b/packages/yet_another_json_isolate/lib/yet_another_json_isolate.dart index f4c26595a..ccb4a4489 100644 --- a/packages/yet_another_json_isolate/lib/yet_another_json_isolate.dart +++ b/packages/yet_another_json_isolate/lib/yet_another_json_isolate.dart @@ -1,6 +1,9 @@ /// JSON encoding and decoding that never blocks the calling isolate for /// long: small payloads are processed inline, large payloads on short lived /// isolates that hand their result back without copying. +/// +/// On web there are no isolates, so every payload is processed inline on the +/// calling thread. library; export 'src/async_json_codec.dart'; diff --git a/packages/yet_another_json_isolate/pubspec.yaml b/packages/yet_another_json_isolate/pubspec.yaml index 59b860bf5..ff777663c 100644 --- a/packages/yet_another_json_isolate/pubspec.yaml +++ b/packages/yet_another_json_isolate/pubspec.yaml @@ -1,5 +1,5 @@ name: yet_another_json_isolate -description: Package for JSON parsing off the main isolate, processing small payloads inline and large payloads on short lived isolates without copying results. +description: JSON parsing off the main isolate, processing small payloads inline and large payloads on short lived isolates without copying results. Runs inline on web. version: 3.0.0-dev.2 homepage: 'https://supabase.com' repository: 'https://github.com/supabase/supabase-flutter/tree/main/packages/yet_another_json_isolate' diff --git a/packages/yet_another_json_isolate/test/yet_another_json_isolate_io_test.dart b/packages/yet_another_json_isolate/test/yet_another_json_isolate_io_test.dart index 17660f258..e8307c38e 100644 --- a/packages/yet_another_json_isolate/test/yet_another_json_isolate_io_test.dart +++ b/packages/yet_another_json_isolate/test/yet_another_json_isolate_io_test.dart @@ -2,6 +2,7 @@ library; import 'dart:async'; +import 'dart:collection'; import 'dart:convert'; import 'dart:isolate'; @@ -16,6 +17,54 @@ class _UnsendableButEncodable { Map toJson() => {'type': 'unsendable'}; } +/// Can be sent to another isolate, but throws from [toJson] an error that +/// cannot be. +class _ThrowsUnsendable { + const _ThrowsUnsendable(); + + /// The ports created on this isolate, so that a test can close them. + static final List ports = []; + + Object toJson() { + final port = ReceivePort(); + ports.add(port); + throw _UnsendableError(port); + } +} + +class _UnsendableError extends Error { + _UnsendableError(this.port); + + final ReceivePort port; + + @override + String toString() => 'Unsendable error'; +} + +/// A JSON object that cannot be sent to another isolate because it holds a +/// [ReceivePort]. +class _UnsendableMap extends MapBase { + _UnsendableMap(this._entries); + + final Map _entries; + final ReceivePort port = ReceivePort(); + + @override + Object? operator [](Object? key) => _entries[key]; + + @override + void operator []=(String key, Object? value) => _entries[key] = value; + + @override + void clear() => _entries.clear(); + + @override + Iterable get keys => _entries.keys; + + @override + Object? remove(Object? key) => _entries.remove(key); +} + /// Every disposal in this group is bounded, so a regression that makes /// `dispose()` wait forever fails the test instead of hanging the suite. Future dispose(YAJsonIsolate isolate) => @@ -23,18 +72,6 @@ Future dispose(YAJsonIsolate isolate) => void main() { group('io implementation', () { - test('throws when initialize is called twice', () async { - final isolate = YAJsonIsolate(); - await isolate.initialize(); - addTearDown(() => dispose(isolate)); - expect(isolate.initialize(), throwsA(isA())); - }); - - test('exposes the provided debug name', () { - final isolate = YAJsonIsolate(debugName: 'my-isolate'); - expect(isolate.debugName, 'my-isolate'); - }); - test('dispose completes when the isolate was never used', () async { final isolate = YAJsonIsolate(); await expectLater(dispose(isolate), completes); @@ -68,7 +105,6 @@ void main() { expect(isolate.decode('{}'), throwsStateError); expect(isolate.encode({}), throwsStateError); - expect(isolate.initialize(), throwsStateError); }); test('a never used isolate also rejects work after dispose', () async { @@ -98,34 +134,81 @@ void main() { await pending; }); - test('encodes an unsendable value inline', () async { + test('encodes a large structure holding an unsendable value', () async { final isolate = YAJsonIsolate(); addTearDown(() => dispose(isolate)); final value = _UnsendableButEncodable(); addTearDown(value.port.close); + final large = [ + for (var i = 0; i < 5000; i++) {'id': i, 'name': 'user_$i'}, + value, + ]; + + final encoded = await isolate.encode(large); + final decoded = jsonDecode(encoded) as List; + expect(decoded, hasLength(5001)); + expect(decoded.first, {'id': 0, 'name': 'user_0'}); + expect(decoded[4999], {'id': 4999, 'name': 'user_4999'}); + expect(decoded.last, {'type': 'unsendable'}); + }); + + test('encodes a large unsendable map inline', () async { + final map = _UnsendableMap({ + for (var i = 0; i < 5000; i++) 'user_$i': {'id': i}, + }); + addTearDown(map.port.close); + final isolate = YAJsonIsolate(); + addTearDown(() => dispose(isolate)); + + final decoded = jsonDecode(await isolate.encode(map)) as Map; + expect(decoded, hasLength(5000)); + expect(decoded['user_4999'], {'id': 4999}); + }); + + test('reports an unencodable value without an isolate', () async { + final isolate = YAJsonIsolate(); + addTearDown(() => dispose(isolate)); + addTearDown(() { + for (final port in _ThrowsUnsendable.ports) { + port.close(); + } + }); + + await expectLater( + isolate.encode([const _ThrowsUnsendable()]), + throwsA( + isA().having( + (error) => error.cause, + 'cause', + isA<_UnsendableError>(), + ), + ), + ); + }); + + test('encodes a structure deeper than the conversion limit', () async { + final isolate = YAJsonIsolate(); + addTearDown(() => dispose(isolate)); + Object? nested = 'leaf'; + for (var i = 0; i < 600; i++) { + nested = [nested]; + } - expect(await isolate.encode(value), '{"type":"unsendable"}'); + final encoded = await isolate.encode(nested); + expect(encoded, '${'[' * 600}"leaf"${']' * 600}'); }); - test( - 'encodes a large structure holding an unsendable value inline', - () async { - final isolate = YAJsonIsolate(); - addTearDown(() => dispose(isolate)); - final value = _UnsendableButEncodable(); - addTearDown(value.port.close); - final large = [ - for (var i = 0; i < 5000; i++) {'id': i, 'name': 'user_$i'}, - value, - ]; - - final encoded = await isolate.encode(large); - final decoded = jsonDecode(encoded) as List; - expect(decoded, hasLength(5001)); - expect(decoded.first, {'id': 0, 'name': 'user_0'}); - expect(decoded[4999], {'id': 4999, 'name': 'user_4999'}); - expect(decoded.last, {'type': 'unsendable'}); - }, - ); + test('throws for a cyclic structure', () async { + final isolate = YAJsonIsolate(); + addTearDown(() => dispose(isolate)); + final inner = []; + final cyclic = [inner]; + inner.add(cyclic); + + await expectLater( + isolate.encode(cyclic), + throwsA(isA()), + ); + }); }); } diff --git a/packages/yet_another_json_isolate/test/yet_another_json_isolate_test.dart b/packages/yet_another_json_isolate/test/yet_another_json_isolate_test.dart index 2f5e9d917..4c0b00702 100644 --- a/packages/yet_another_json_isolate/test/yet_another_json_isolate_test.dart +++ b/packages/yet_another_json_isolate/test/yet_another_json_isolate_test.dart @@ -18,13 +18,50 @@ final _largeValue = List.generate( }, ); +class _Book { + _Book(this.title); + + final String title; + int toJsonCalls = 0; + + Map toJson() { + toJsonCalls++; + return {'title': title}; + } +} + +class _Catalog { + _Catalog(this.rows); + + final List> rows; + int toJsonCalls = 0; + + List> toJson() { + toJsonCalls++; + return rows; + } +} + +class _Throwing { + const _Throwing(); + + Object toJson() => throw StateError('not serializable'); +} + +class _Wrapping { + const _Wrapping(this.value); + + final Object value; + + Object toJson() => value; +} + void main() { late YAJsonIsolate isolate; - group('with manual initialize', () { - setUp(() async { + group('basics', () { + setUp(() { isolate = YAJsonIsolate(); - await isolate.initialize(); }); tearDown(() async { @@ -38,9 +75,16 @@ void main() { test('encodes a JSON object', () async { expect(await isolate.encode(_jsonMap), _jsonString); }); + + test('consumes the value before the caller can mutate it', () async { + final value = {'a': 1}; + final pending = isolate.encode(value); + value['a'] = 2; + expect(await pending, '{"a":1}'); + }); }); - group('without manual initialize', () { + group('objects with toJson', () { setUp(() { isolate = YAJsonIsolate(); }); @@ -49,12 +93,75 @@ void main() { await isolate.dispose(); }); - test('decodes lazily on first call', () async { - expect(await isolate.decode(_jsonString), _jsonMap); + test('calls toJson once on the calling isolate', () async { + final book = _Book('Dune'); + expect(await isolate.encode(book), '{"title":"Dune"}'); + expect(book.toJsonCalls, 1); }); - test('encodes lazily on first call', () async { - expect(await isolate.encode(_jsonMap), _jsonString); + test('calls toJson on objects nested in lists and maps', () async { + final first = _Book('Dune'); + final second = _Book('Emma'); + final encoded = await isolate.encode({ + 'books': [first, second], + 'featured': first, + }); + expect( + encoded, + '{"books":[{"title":"Dune"},{"title":"Emma"}],' + '"featured":{"title":"Dune"}}', + ); + expect(first.toJsonCalls, 2); + expect(second.toJsonCalls, 1); + }); + + test('calls toJson on the calling isolate for a large object', () async { + final catalog = _Catalog(_largeValue); + final encoded = await isolate.encode(catalog); + expect(encoded.length, greaterThan(64 * 1024)); + expect(jsonDecode(encoded), _largeValue); + expect(catalog.toJsonCalls, 1); + }); + + test('calls toJson on objects inside a large structure', () async { + final book = _Book('Dune'); + final encoded = await isolate.encode([..._largeValue, book]); + expect((jsonDecode(encoded) as List).last, {'title': 'Dune'}); + expect(book.toJsonCalls, 1); + }); + + test('leaves the original structure untouched', () async { + final value = {'book': _Book('Dune')}; + await isolate.encode(value); + expect(value['book'], isA<_Book>()); + }); + + test('throws when toJson throws', () async { + await expectLater( + isolate.encode(const _Throwing()), + throwsA(isA()), + ); + }); + + test('throws when toJson returns an unencodable value', () async { + await expectLater( + isolate.encode([_Wrapping(DateTime(2026))]), + throwsA(isA()), + ); + }); + + test('throws for a map with keys that are not strings', () async { + await expectLater( + isolate.encode({1: _Book('Dune')}), + throwsA(isA()), + ); + }); + + test('throws for a number that is not finite', () async { + await expectLater( + isolate.encode([double.nan]), + throwsA(isA()), + ); }); }); @@ -250,9 +357,8 @@ void main() { }); group('concurrency and ordering', () { - setUp(() async { + setUp(() { isolate = YAJsonIsolate(); - await isolate.initialize(); }); tearDown(() async { @@ -295,6 +401,28 @@ void main() { }); group('lifecycle', () { + test('every operation throws after dispose', () async { + final disposed = YAJsonIsolate(); + await disposed.dispose(); + + await expectLater(disposed.decode('{}'), throwsStateError); + await expectLater( + disposed.decodeBytes(utf8.encode('{}')), + throwsStateError, + ); + await expectLater(disposed.encode({}), throwsStateError); + }); + + test('dispose can be called more than once', () async { + final disposed = YAJsonIsolate(); + await disposed.dispose(); + await expectLater(disposed.dispose(), completes); + }); + + test('exposes the provided debug name', () { + expect(YAJsonIsolate(debugName: 'json').debugName, 'json'); + }); + test('dispose can be awaited on a lazily initialized isolate', () async { final lazyIsolate = YAJsonIsolate(); await lazyIsolate.decode(_jsonString); diff --git a/sdk-compliance.yaml b/sdk-compliance.yaml index b24ca7dd3..592316ef8 100644 --- a/sdk-compliance.yaml +++ b/sdk-compliance.yaml @@ -3576,4 +3576,3 @@ supporting_symbols: - YAJsonIsolate.decodeBytes - YAJsonIsolate.dispose - YAJsonIsolate.encode - - YAJsonIsolate.initialize