provision method

Installs the verified model in directory unless it is already there.

The stream ends with ModelProvisioned, or with an error and nothing installed. A model already in place is reported without a request. Otherwise the model is downloaded from the target's source, with ModelDownloading as bytes arrive. cancel, or cancelling the subscription, stops the download. Either way the temporary file is removed before the stream ends or the cancellation completes, and cancel ends the stream with a cancelled error. A failed or cancelled download leaves any existing file at the target untouched.

It also removes the temporary files of downloads that stopped at least a day ago without removing them, such as one whose process was killed. A download in progress writes far more often, so its file is kept.

Implementation

Stream<ModelProvisionProgress> provision({WayfinderCancellation? cancel}) {
  final stop = Completer<void>();
  void halt() {
    if (!stop.isCompleted) stop.complete();
  }

  late final StreamController<ModelProvisionProgress> events;
  Future<void>? running;
  events = StreamController<ModelProvisionProgress>(
    onListen: () {
      if (cancel != null) unawaited(cancel.whenCancelled.then((_) => halt()));
      running = _provision(events.add, stop.future, cancel)
          .then<void>(
            (_) {},
            onError: (Object error, StackTrace stackTrace) =>
                events.addError(error, stackTrace),
          )
          .whenComplete(() => unawaited(events.close()));
    },
    onCancel: () {
      halt();
      return running;
    },
  );
  return events.stream;
}