initialize method

Future<bool> initialize()

Initializes the worker isolate and ODBC environment.

  1. Spawns a new isolate via Isolate.spawn.
  2. Loads the ODBC driver in the worker.
  3. Initializes the ODBC environment there.
  4. Returns when the worker is ready to accept requests.

One-time cost is typically ~50–100 ms. Safe to call multiple times; later calls return immediately if already initialized.

Returns true if initialization succeeds, false otherwise.

Implementation

Future<bool> initialize() async {
  if (_isInitialized) return true;
  _isShuttingDown = false;

  final handshake = Completer<SendPort>();
  _receivePort = ReceivePort();
  _receivePort!.listen(
    (message) {
      if (message is SendPort) {
        if (!handshake.isCompleted) handshake.complete(message);
      } else if (message is WorkerResponse) {
        _handleResponse(message);
      }
    },
    onError: (Object error, StackTrace stackTrace) async {
      _failAllPending(
        AsyncError(
          code: AsyncErrorCode.workerTerminated,
          message: 'Worker isolate error: $error',
        ),
      );
      await _triggerAutoRecovery(
        reason: 'Worker isolate crashed',
        error: error,
        stackTrace: stackTrace,
      );
    },
    onDone: () async {
      if (_pendingRequests.isNotEmpty) {
        _failAllPending(
          const AsyncError(
            code: AsyncErrorCode.workerTerminated,
            message: 'Worker isolate terminated',
          ),
        );
      }
      await _triggerAutoRecovery(reason: 'Worker isolate terminated');
    },
  );

  _workerIsolate = await Isolate.spawn(
    _isolateEntry ?? workerEntry,
    _receivePort!.sendPort,
  );
  _workerSendPort = await handshake.future;

  final initResp = await _sendRequest<InitializeResponse>(
    InitializeRequest(_nextRequestId()),
  );
  return _isInitialized = initResp.success;
}