Skip to content
Merged
Show file tree
Hide file tree
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
5 changes: 5 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 5 additions & 1 deletion MIGRATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
2 changes: 1 addition & 1 deletion packages/postgrest/lib/src/postgrest.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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(
() =>
Expand Down
2 changes: 1 addition & 1 deletion packages/supabase/lib/src/supabase_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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 &&
Expand Down
1 change: 0 additions & 1 deletion packages/supabase/test/client_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion packages/yet_another_json_isolate/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<h1 align="center">yet_another_json_isolate</h1>

<p align="center">
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.
</p>
</p>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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++) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
199 changes: 125 additions & 74 deletions packages/yet_another_json_isolate/lib/src/json_isolate_io.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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<List<int>, Object?> _utf8JsonDecoder = const Utf8Decoder().fuse(
const JsonDecoder(),
Expand All @@ -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<void>? _disposal;
final Set<Future<void>> _activeWork = {};

Expand All @@ -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<void> 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
Expand Down Expand Up @@ -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<String> 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<dynamic> 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<dynamic, dynamic> 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<dynamic> list:
budget -= 2;
List<Object?>? 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<dynamic, dynamic> map:
budget -= 2;
Map<String, Object?>? 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<dynamic> _ ||
Map<dynamic, dynamic> _ => convert(json, depth + 1),
_ => _unencodable,
};
}
}
}
Loading
Loading