2024-04-20 23:20:52 +00:00
|
|
|
import 'package:grpc/grpc.dart';
|
2024-04-21 18:58:45 +00:00
|
|
|
import 'package:path_provider/path_provider.dart';
|
2024-04-20 23:20:52 +00:00
|
|
|
import 'cw_mweb_platform_interface.dart';
|
|
|
|
import 'mwebd.pbgrpc.dart';
|
|
|
|
|
|
|
|
class CwMweb {
|
2024-07-25 14:03:40 +00:00
|
|
|
static RpcClient? _rpcClient;
|
|
|
|
static ClientChannel? _clientChannel;
|
2024-07-26 19:34:11 +00:00
|
|
|
static int? _port;
|
2024-07-25 14:03:40 +00:00
|
|
|
|
2024-07-26 19:34:11 +00:00
|
|
|
static Future<void> _initializeClient() async {
|
2024-04-21 18:58:45 +00:00
|
|
|
final appDir = await getApplicationSupportDirectory();
|
2024-07-26 19:34:11 +00:00
|
|
|
_port = await CwMwebPlatform.instance.start(appDir.path);
|
|
|
|
if (_port == null || _port == 0) {
|
|
|
|
throw Exception("Failed to start server");
|
|
|
|
}
|
|
|
|
print("Attempting to connect to server on port: $_port");
|
|
|
|
|
2024-07-25 14:03:40 +00:00
|
|
|
_clientChannel = ClientChannel('127.0.0.1',
|
2024-07-26 19:34:11 +00:00
|
|
|
port: _port!,
|
2024-07-25 14:03:40 +00:00
|
|
|
options: const ChannelOptions(
|
|
|
|
credentials: ChannelCredentials.insecure(),
|
|
|
|
keepAlive: ClientKeepAliveOptions(permitWithoutCalls: true),
|
|
|
|
));
|
|
|
|
_rpcClient = RpcClient(_clientChannel!);
|
2024-07-26 19:34:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
static Future<RpcClient> stub({int maxRetries = 3}) async {
|
|
|
|
for (int i = 0; i < maxRetries; i++) {
|
|
|
|
try {
|
|
|
|
if (_rpcClient == null || _clientChannel == null) {
|
|
|
|
await _initializeClient();
|
|
|
|
} else {
|
|
|
|
// Try to use the existing connection
|
|
|
|
var status = await _rpcClient!
|
|
|
|
.status(StatusRequest(), options: CallOptions(timeout: const Duration(seconds: 10)));
|
|
|
|
if (status != null) {
|
|
|
|
return _rpcClient!;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} catch (e) {
|
|
|
|
print("Attempt $i failed: $e");
|
|
|
|
if (i == maxRetries - 1) rethrow;
|
|
|
|
await stop();// call stop so we create a new instance before retrying
|
|
|
|
await Future.delayed(Duration(seconds: 2)); // Wait before retrying
|
|
|
|
}
|
|
|
|
}
|
|
|
|
throw Exception("Failed to connect after $maxRetries attempts");
|
2024-07-17 16:27:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
static Future<void> stop() async {
|
2024-07-26 19:34:11 +00:00
|
|
|
await CwMwebPlatform.instance.stop();
|
2024-07-25 14:03:40 +00:00
|
|
|
await cleanup();
|
|
|
|
}
|
|
|
|
|
|
|
|
static Future<void> cleanup() async {
|
|
|
|
await _clientChannel?.terminate();
|
|
|
|
_rpcClient = null;
|
|
|
|
_clientChannel = null;
|
2024-07-26 19:34:11 +00:00
|
|
|
_port = null;
|
2024-04-20 23:20:52 +00:00
|
|
|
}
|
|
|
|
}
|