[Bug] [^2.4.0] DriftIsolate - cannot connect from background isolate
Hi,
I believe version 2.4.0 introduced a bug when trying to establish a connection using DriftIsolate from within background isolate (using workmanager). Here is code sample:
var driftIsolate = await _ensureDriftIsolate();
var connection = await driftIsolate.connect();
var database = DriftContext.connect(connection); <= app hangs here, but only in background isolate (it works in foreground)
// this is the new constructor
DriftContext.connect(DatabaseConnection connection) : super.connect(connection); // I know it has been changed in v2.5.0
Future<DriftIsolate> _ensureDriftIsolate() async {
final dir = await getApplicationDocumentsDirectory();
final path = p.join(dir.path, 'filename.sqlite');
var driftPort = IsolateNameServer.lookupPortByName("somePortName");
if (driftPort == null) {
final receivePort = ReceivePort();
IsolateNameServer.registerPortWithName(receivePort.sendPort, driftPortName);
await Isolate.spawn(_startBackground, _IsolateStartRequest(receivePort.sendPort, path));
final firstMessage = await receivePort.first;
driftPort = firstMessage as SendPort;
}
return DriftIsolate.fromConnectPort(driftPort);
}
void _startBackground(_IsolateStartRequest request) {
final driftIsolate = DriftIsolate.inCurrent(() => DatabaseConnection(LazyDatabase(() async {
setupSqlCipher();
final file = File(request.targetPath);
return NativeDatabase(file, logStatements: false, setup: (rawDb) {
assert(_debugCheckHasCipher(rawDb));
rawDb.execute("PRAGMA key = 'secretPassword';");
});
})));
// inform the starting isolate about this, so that it can call .connect()
request.sendDriftIsolate.send(driftIsolate.connectPort);
}
Everything works in version 2.3.0
Regards
Thanks for the report! I've tried to reproduce this in the repro-2319 branch in this directory. Unfortunately I couldn't quite get the setup to work - it seems like the isolate name server is not shared between the foreground isolate and workmanager - it spawns a new drift isolate each time, but otherwise works.
Could you provide more information on how to reproduce this (maybe fork this repository and finish the repro in that branch)?
This only works if the background isolate is started in the same VM. Something might have changed in the workmanager library.
There has been no activity in this issue for over a year and no reproducible bug exists.