Skip to content
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

Basic Refactoring: Type Annotations, Final & Const Usage #33

Merged
merged 15 commits into from
Nov 2, 2024
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
30 changes: 18 additions & 12 deletions benchmark/benchmark.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,23 @@ import '../test/isolate_manager_test.dart';
// dart test --platform=chrome "benchmark/benchmark.dart"

void main() {
test('benchmark', () async {
print('|Fibonacci|Main App|One Isolate|Three Isolates|Isolate.run|');
print('|:-:|-:|-:|-:|-:|');
test(
'benchmark',
() async {
print('|Fibonacci|Main App|One Isolate|Three Isolates|Isolate.run|');
print('|:-:|-:|-:|-:|-:|');

// Fibonacci 30
await execute(30);
// Fibonacci 30
await execute(30);

// Fibonacci 33
await execute(33);
// Fibonacci 33
await execute(33);

// Fibonacci 36
await execute(36);
}, timeout: Timeout(Duration(seconds: 120)));
// Fibonacci 36
await execute(36);
},
timeout: const Timeout(Duration(seconds: 120)),
);
}

Future<void> execute(int fibonacciNumber) async {
Expand Down Expand Up @@ -65,7 +69,8 @@ Future<void> execute(int fibonacciNumber) async {

stopWatch.start();
await Future.wait(
[for (int i = 0; i < 70; i++) threeIsolates.compute(fibonacciNumber)]);
[for (int i = 0; i < 70; i++) threeIsolates.compute(fibonacciNumber)],
);
threeIsolatesInIsolate = stopWatch.elapsed;
stopWatch
..stop()
Expand All @@ -86,5 +91,6 @@ Future<void> execute(int fibonacciNumber) async {
}

print(
'|$fibonacciNumber|${singleInMain.inMicroseconds}|${singleInIsolate.inMicroseconds}|${threeIsolatesInIsolate.inMicroseconds}|${runMethodInIsolate.inMicroseconds}|');
'|$fibonacciNumber|${singleInMain.inMicroseconds}|${singleInIsolate.inMicroseconds}|${threeIsolatesInIsolate.inMicroseconds}|${runMethodInIsolate.inMicroseconds}|',
);
}
14 changes: 8 additions & 6 deletions bin/generate_shared.dart
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,10 @@ Future<void> generate(ArgResults argResults, List<String> dartArgs) async {
final isolateManager = IsolateManager.create(
_getAndGenerateFromAnotatedFunctions,
concurrent: 3,
)..start();
);
await isolateManager.start();

List<List<dynamic>> params = [];
final params = <List<dynamic>>[];
for (final file in allFiles) {
if (file is File && file.path.endsWith('.dart')) {
final filePath = file.absolute.path;
Expand All @@ -57,15 +58,15 @@ Future<void> generate(ArgResults argResults, List<String> dartArgs) async {

print('Total files to generate: ${params.length}');

Map<String, String> anotatedFunctions = {};
final anotatedFunctions = <String, String>{};
int counter = 0;
await Future.wait(
[
for (final param in params)
isolateManager.compute(param).then((value) {
counter += value.length;
anotatedFunctions.addAll(value);
})
}),
],
);

Expand All @@ -89,8 +90,9 @@ Future<void> generate(ArgResults argResults, List<String> dartArgs) async {
}

Future<Map<String, String>> _getAndGenerateFromAnotatedFunctions(
List<dynamic> params) async {
String filePath = params[0];
List<dynamic> params,
) async {
final String filePath = params[0];

return _getAnotatedFunctions(filePath);
}
Expand Down
31 changes: 18 additions & 13 deletions bin/generate_single.dart
Original file line number Diff line number Diff line change
Expand Up @@ -39,19 +39,21 @@ Future<void> generate(ArgResults argResults, List<String> dartArgs) async {
return;
}

final List<FileSystemEntity> allFiles = _listAllFiles(Directory(input), []);
final allFiles = _listAllFiles(Directory(input), []);
final isolateManager = IsolateManager.create(
_getAndGenerateFromAnotatedFunctions,
concurrent: 3,
)..start();
);
await isolateManager.start();

List<List<dynamic>> params = [];
final params = <List<dynamic>>[];
for (final file in allFiles) {
if (file is File && file.path.endsWith('.dart')) {
final filePath = file.absolute.path;
final content = await file.readAsString();
final pattern = RegExp(
'(@$classAnnotation|@$constAnnotation|@$constCustomWorkerAnnotation)');
'(@$classAnnotation|@$constAnnotation|@$constCustomWorkerAnnotation)',
);
if (content.contains(pattern)) {
params.add(
<dynamic>[
Expand All @@ -71,12 +73,10 @@ Future<void> generate(ArgResults argResults, List<String> dartArgs) async {
print('Total files to generate: ${params.length}');

int counter = 0;
await Future.wait(
[
for (final param in params)
isolateManager.compute(param).then((value) => counter += value)
],
);
await Future.wait([
for (final param in params)
isolateManager.compute(param).then((value) => counter += value),
]);

print('Total generated functions: $counter');

Expand Down Expand Up @@ -203,7 +203,8 @@ Future<void> _generateFromAnotatedFunction(
sink.writeln('main() {');
if (function.value.isCustomWorker) {
sink.writeln(
' IsolateManagerFunction.customWorkerFunction(${function.key});');
' IsolateManagerFunction.customWorkerFunction(${function.key});',
);
} else {
sink.writeln(' IsolateManagerFunction.workerFunction(${function.key});');
}
Expand Down Expand Up @@ -247,7 +248,9 @@ Future<void> _generateFromAnotatedFunction(

if (await outputFile.exists()) {
print(
'Path: ${p.relative(sourceFilePath)} => Function: ${function.key} => Compiled: ${p.relative(outputPath)}');
'Path: ${p.relative(sourceFilePath)} => '
'Function: ${function.key} => Compiled: ${p.relative(outputPath)}',
);
if (!isDebug) {
if (isWasm) {
await File('$output/$name.unopt.wasm').delete();
Expand All @@ -257,7 +260,9 @@ Future<void> _generateFromAnotatedFunction(
}
} else {
print(
'Path: ${p.relative(sourceFilePath)} => Function: ${function.key} => Compile ERROR: ${p.relative(outputPath)}');
'Path: ${p.relative(sourceFilePath)} => Function: '
'${function.key} => Compile ERROR: ${p.relative(outputPath)}',
);
final r = result.stdout.toString().split('\n');
for (var element in r) {
print(' > $element');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,7 @@ class IsolateContactorInternal<R, P> extends IsolateContactor<R, P> {
required IsolateConverter<R> workerConverter,
bool debugMode = false,
}) async {
IsolateContactorInternal<R, P> isolateContactor =
IsolateContactorInternal._(
final isolateContactor = IsolateContactorInternal<R, P>._(
isolateFunction: isolateFunction,
workerName: workerName,
isolateParam: initialParams,
Expand All @@ -81,13 +80,15 @@ class IsolateContactorInternal<R, P> extends IsolateContactor<R, P> {
_isolateContactorController.onMessage.listen((message) {
printDebug(() => 'Message received from Isolate: $message');
_mainStreamController.sink.add(message);
}).onError((err, stack) {
}).onError((Object err, StackTrace stack) {
printDebug(() => 'Error message received from Isolate: $err');
_mainStreamController.sink.addError(err, stack);
});

_isolate = await Isolate.spawn(
_isolateFunction, [_isolateParam, _receivePort.sendPort]);
_isolateFunction,
[_isolateParam, _receivePort.sendPort],
);

await _isolateContactorController.ensureInitialized.future;
printDebug(() => 'Initialized');
Expand Down Expand Up @@ -119,16 +120,16 @@ class IsolateContactorInternal<R, P> extends IsolateContactor<R, P> {
@override
Future<R> sendMessage(P message) async {
final Completer<R> completer = Completer();
StreamSubscription? sub;
late final StreamSubscription<R> sub;
sub = _isolateContactorController.onMessage.listen((result) async {
if (!completer.isCompleted) {
completer.complete(result);
await sub?.cancel();
await sub.cancel();
}
})
..onError((err, stack) async {
..onError((Object err, StackTrace stack) async {
completer.completeError(err, stack);
await sub?.cancel();
await sub.cancel();
});

printDebug(() => 'Message send to isolate: $message');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ abstract class IsolateContactorInternal<R, P> extends IsolateContactor<R, P> {
} catch (_) {
if (debugMode) {
print(
'[${IsolateContactor.debugLogPrefix}]: This browser doesn\'t support Worker, Future will be applied!');
'[${IsolateContactor.debugLogPrefix}]: This browser doesn\'t support Worker, Future will be applied!',
);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ class IsolateContactorInternalFuture<R, P>
_workerName = workerName,
_isolateParam = isolateParam,
_isolateContactorController = IsolateContactorControllerImpl(
StreamController.broadcast(),
StreamController<dynamic>.broadcast(),
converter: converter,
workerConverter: workerConverter,
onDispose: null,
Expand All @@ -50,8 +50,7 @@ class IsolateContactorInternalFuture<R, P>
required IsolateConverter<R> workerConverter,
bool debugMode = false,
}) async {
IsolateContactorInternalFuture<R, P> isolateContactor =
IsolateContactorInternalFuture._(
final isolateContactor = IsolateContactorInternalFuture<R, P>._(
isolateFunction: isolateFunction,
workerName: isolateFunctionName,
isolateParam: initialParams ?? [],
Expand All @@ -72,7 +71,7 @@ class IsolateContactorInternalFuture<R, P>
() => '[Main Stream] Message received from Future: $message',
);
_mainStreamController.sink.add(message);
}).onError((err, stack) {
}).onError((Object err, StackTrace stack) {
printDebug(
() => '[Main Stream] Error message received from Future: $err',
);
Expand Down Expand Up @@ -115,16 +114,16 @@ class IsolateContactorInternalFuture<R, P>
}

final Completer<R> completer = Completer();
StreamSubscription? sub;
late final StreamSubscription<R> sub;
sub = _isolateContactorController.onMessage.listen((result) async {
if (!completer.isCompleted) {
completer.complete(result);
await sub?.cancel();
await sub.cancel();
}
})
..onError((err, stack) async {
..onError((Object err, StackTrace stack) async {
completer.completeError(err, stack);
await sub?.cancel();
await sub.cancel();
});

printDebug(() => 'Message send to isolate: $message');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,7 @@ class IsolateContactorInternalWorker<R, P>
required IsolateConverter<R> workerConverter,
bool debugMode = false,
}) async {
IsolateContactorInternalWorker<R, P> isolateContactor =
IsolateContactorInternalWorker._(
final isolateContactor = IsolateContactorInternalWorker<R, P>._(
isolateFunction: isolateFunction,
workerName: workerName,
isolateParam: initialParams,
Expand All @@ -79,7 +78,7 @@ class IsolateContactorInternalWorker<R, P>
() => '[Main Stream] Message received from Worker: $message',
);
_mainStreamController.sink.add(message);
}).onError((err, stack) {
}).onError((Object err, StackTrace stack) {
printDebug(
() => '[Main Stream] Error message received from Worker: $err',
);
Expand Down Expand Up @@ -122,16 +121,16 @@ class IsolateContactorInternalWorker<R, P>
}

final Completer<R> completer = Completer();
StreamSubscription? sub;
late final StreamSubscription<R> sub;
sub = _isolateContactorController!.onMessage.listen((result) async {
if (!completer.isCompleted) {
completer.complete(result);
await sub?.cancel();
await sub.cancel();
}
})
..onError((err, stack) async {
..onError((Object err, StackTrace stack) async {
completer.completeError(err, stack);
await sub?.cancel();
await sub.cancel();
});

printDebug(() => 'Message send to isolate: $message');
Expand Down
2 changes: 1 addition & 1 deletion lib/src/base/contactor/isolate_contactor_controller.dart
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ abstract class IsolateContactorController<R, P> {
/// `params` is the default parameters of the isolate function.
dynamic params, {
/// `onDispose` is called when the controller is disposed.
Function()? onDispose,
void Function()? onDispose,
}) {
// This method is not used in this controller
R converter(dynamic value) => value;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ import '../models/exception.dart';

class IsolateContactorControllerImpl<R, P>
implements IsolateContactorController<R, P> {
final IsolateChannel _delegate;
StreamSubscription? _delegateSubscription;
final IsolateChannel<Map<IsolatePort, dynamic>> _delegate;
late final StreamSubscription<Map<IsolatePort, dynamic>> _delegateSubscription;

final StreamController<R> _mainStreamController =
StreamController.broadcast();
Expand All @@ -35,7 +35,7 @@ class IsolateContactorControllerImpl<R, P>
: IsolateChannel.connectReceive(params),
_initialParams = params is List ? params.first : null {
_delegateSubscription = _delegate.stream.listen((event) {
(event as Map<IsolatePort, dynamic>).forEach((key, value) {
event.forEach((key, value) {
switch (key) {
case IsolatePort.main:
if (value is IsolateException) {
Expand Down Expand Up @@ -103,7 +103,7 @@ class IsolateContactorControllerImpl<R, P>
@override
Future<void> close() async {
await Future.wait([
_delegateSubscription!.cancel(),
_delegateSubscription.cancel(),
_mainStreamController.close(),
_isolateStreamController.close(),
]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import '../isolate_contactor_controller_web.dart';

class IsolateContactorControllerImplFuture<R, P>
implements IsolateContactorControllerImpl<R, P> {
final StreamController _delegate;
final StreamController<dynamic> _delegate;

final StreamController<R> _mainStreamController =
StreamController.broadcast();
Expand Down Expand Up @@ -65,7 +65,7 @@ class IsolateContactorControllerImplFuture<R, P>

/// Get this StreamController
@override
StreamController get controller => _delegate;
StreamController<dynamic> get controller => _delegate;

/// Get initial params for `createCustom`
@override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,9 @@ class IsolateContactorControllerImplWorker<R, P>
if (IsolateException.isValidObject(data)) {
final exception = IsolateException.fromJson(data);
_mainStreamController.addError(
exception.error.toString(), StackTrace.empty);
exception.error.toString(),
StackTrace.empty,
);
return;
}

Expand Down
Loading
Loading