Skip to content

An open-source cross-platform alternative to AirDrop

refactor: move staged discovery to core

Tien Do Namf5baa1430949
diff --git a/app/lib/pages/tabs/send_tab.dart b/app/lib/pages/tabs/send_tab.dart
index 9a061825..3fd71cdc 100644
--- a/app/lib/pages/tabs/send_tab.dart
+++ b/app/lib/pages/tabs/send_tab.dart
@@ -338,7 +338,7 @@ class _ScanButton extends StatelessWidget {
child: CustomIconButton(
onPressed: () async {
context.redux(nearbyDevicesProvider).dispatch(ClearFoundDevicesAction());
- await context.global.dispatchAsync(StartSmartScan(forceLegacy: true));
+ await context.global.dispatchAsync(StartSmartScan());
},
child: Icon(Icons.sync, color: iconColor),
),
diff --git a/app/lib/pages/tabs/send_tab_vm.dart b/app/lib/pages/tabs/send_tab_vm.dart
index e9775aa2..1c93459f 100644
--- a/app/lib/pages/tabs/send_tab_vm.dart
+++ b/app/lib/pages/tabs/send_tab_vm.dart
@@ -206,7 +206,7 @@ class SendTabInitAction extends AsyncGlobalAction {
Future<void> reduce() async {
final devices = ref.read(nearbyDevicesProvider).devices;
if (devices.isEmpty) {
- await dispatchAsync(StartSmartScan(forceLegacy: false));
+ await dispatchAsync(StartSmartScan());
}
}
}
diff --git a/app/lib/provider/network/nearby_devices_provider.dart b/app/lib/provider/network/nearby_devices_provider.dart
index f83fbb5f..21410822 100644
--- a/app/lib/provider/network/nearby_devices_provider.dart
+++ b/app/lib/provider/network/nearby_devices_provider.dart
@@ -189,29 +189,39 @@ class StartLegacyScan extends AsyncReduxAction<NearbyDevicesService, NearbyDevic
}
}
-class StartFavoriteScan extends AsyncReduxAction<NearbyDevicesService, NearbyDevicesState> {
- final List<FavoriteDevice> devices;
+/// Discovers devices in stages, cheapest first: multicast announcement and
+/// favorite probes right away, a subnet scan of [interfaces] only when
+/// nothing was confirmed within the grace period.
+/// This method awaits until every stage is finished.
+class StartStagedScan extends AsyncReduxAction<NearbyDevicesService, NearbyDevicesState> {
+ final List<FavoriteDevice> favorites;
+ final List<String> interfaces;
+ final int port;
final bool https;
+ final Duration grace;
- StartFavoriteScan({
- required this.devices,
+ StartStagedScan({
+ required this.favorites,
+ required this.interfaces,
+ required this.port,
required this.https,
+ required this.grace,
});
@override
Future<NearbyDevicesState> reduce() async {
- if (devices.isEmpty) {
- return state;
- }
dispatch(_SetRunningFavoriteScanAction(true));
// The found devices arrive on the [StartDiscoveryListener] stream;
- // this stream only signals when every favorite has been probed.
+ // this stream only signals when every stage has finished.
await external(notifier._isolateController)
.dispatchTakeResult(
- IsolateDiscoveryFavoriteScanAction(
- favorites: devices.map((e) => (e.ip, e.port)).toList(),
+ IsolateDiscoveryStagedScanAction(
+ favorites: favorites.map((e) => (e.ip, e.port)).toList(),
+ networkInterfaces: interfaces,
+ port: port,
https: https,
+ grace: grace,
),
)
.drain<void>();
diff --git a/app/lib/provider/network/scan_facade.dart b/app/lib/provider/network/scan_facade.dart
index 00e0fc24..9f3a1c5c 100644
--- a/app/lib/provider/network/scan_facade.dart
+++ b/app/lib/provider/network/scan_facade.dart
@@ -1,60 +1,36 @@
import 'dart:async';
-import 'package:localsend_app/pages/home_page.dart';
-import 'package:localsend_app/pages/home_page_controller.dart';
import 'package:localsend_app/provider/favorites_provider.dart';
import 'package:localsend_app/provider/local_ip_provider.dart';
import 'package:localsend_app/provider/network/nearby_devices_provider.dart';
import 'package:localsend_app/provider/settings_provider.dart';
-import 'package:localsend_isolates/util/sleep.dart';
import 'package:refena_flutter/refena_flutter.dart';
-/// Scans the network via multicast first,
-/// if no devices has been found, try http-based discovery on the first subnet.
-/// If [forceLegacy] is true, then the http-based discovery runs in parallel.
-/// Otherwise, it runs after a delay of 1 second and only if no devices has been found.
+/// Discovers devices in stages, cheapest first: multicast announcement and
+/// favorite probes right away, http-based discovery on the subnets only when
+/// nothing was confirmed within 1 second.
class StartSmartScan extends AsyncGlobalAction {
/// Maximum number of interfaces to scan.
/// If there are more interfaces, the first ones will be used or the user needs to select one.
static const maxInterfaces = 3;
- final bool forceLegacy;
-
- StartSmartScan({required this.forceLegacy});
-
@override
Future<void> reduce() async {
- // Try performant Multicast/UDP method first
- ref.redux(nearbyDevicesProvider).dispatch(StartMulticastScan());
-
- // At the same time, try to discover favorites
final favorites = ref.read(favoritesProvider);
- final https = ref.read(settingsProvider).https;
- await ref.redux(nearbyDevicesProvider).dispatchAsync(StartFavoriteScan(devices: favorites, https: https));
-
- if (!forceLegacy) {
- // Wait a bit before trying the legacy method.
- // Skip waiting if [forceLegacy] is true.
- await sleepAsync(1000);
- }
-
- // If no devices has been found, then switch to legacy discovery mode
- // which is purely HTTP/TCP based.
- final stillEmpty = ref.read(nearbyDevicesProvider).devices.isEmpty;
- final stillInSendTab = ref.read(homePageControllerProvider).currentTab == HomeTab.send;
- if (forceLegacy || (stillEmpty && stillInSendTab)) {
- final networkInterfaces = ref.read(localIpProvider).localIps.take(maxInterfaces).toList();
- if (networkInterfaces.isNotEmpty) {
- await dispatchAsync(StartLegacySubnetScan(subnets: networkInterfaces));
- }
- } else {
- if (!stillEmpty) {
- emitMessage('Already found devices. This network seem to work, no need to start legacy scan.');
- }
- if (!stillInSendTab) {
- emitMessage('User left the send tab. No need to start legacy scan.');
- }
- }
+ final settings = ref.read(settingsProvider);
+ final networkInterfaces = ref.read(localIpProvider).localIps.take(maxInterfaces).toList();
+
+ await ref
+ .redux(nearbyDevicesProvider)
+ .dispatchAsync(
+ StartStagedScan(
+ favorites: favorites,
+ interfaces: networkInterfaces,
+ port: settings.port,
+ https: settings.https,
+ grace: const Duration(seconds: 1),
+ ),
+ );
}
}
diff --git a/packages/core/src/discovery/mod.rs b/packages/core/src/discovery/mod.rs
index c8e197c2..20cb3900 100644
--- a/packages/core/src/discovery/mod.rs
+++ b/packages/core/src/discovery/mod.rs
@@ -15,7 +15,7 @@ use crate::util::error::ErrorChain;
use futures_util::StreamExt;
use std::collections::HashSet;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
-use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use store::DeviceStore;
@@ -113,6 +113,10 @@ struct DiscoveryState {
/// The interface addresses a subnet scan is currently running for.
scanning: std::sync::Mutex<HashSet<Ipv4Addr>>,
+
+ /// Number of confirmations in this run, on which
+ /// [`DiscoveryHandle::discover_staged`] decides whether to escalate.
+ confirmations: AtomicU64,
}
impl DiscoveryState {
@@ -177,6 +181,7 @@ impl DiscoveryState {
/// emits the resulting event. Returns whether the device is new, and
/// its stored state after the merge.
async fn found(&self, device: DiscoveredDevice) -> (bool, StatefulDevice) {
+ self.confirmations.fetch_add(1, Ordering::Relaxed);
let (event, merged) = self.store.upsert(device, SystemTime::now());
let is_new = matches!(event, DiscoveryEvent::Discovered { .. });
if let Some(event_tx) = &self.event_tx {
@@ -252,6 +257,76 @@ impl DiscoveryHandle {
self.state.probe(&client, host, port, protocol).await
}
+ /// Discovers devices at known addresses, e.g. the favorites, by sending
+ /// each channel a register request: [`DiscoveryHandle::discover`] for a
+ /// whole list, probed concurrently.
+ ///
+ /// Channels that do not answer are skipped; returns the stored state of
+ /// the devices that answered, in completion order.
+ pub async fn discover_known_http_channels(
+ &self,
+ channels: Vec<HttpChannel>,
+ ) -> Result<Vec<StatefulDevice>, ClientError> {
+ let client = self.state.unpinned_client()?;
+
+ let state = &self.state;
+ let client = &client;
+ let found = futures_util::stream::iter(channels)
+ .map(|channel| async move {
+ state
+ .probe(client, &channel.host, channel.port, channel.protocol)
+ .await
+ .ok()
+ .flatten()
+ })
+ .buffer_unordered(SCAN_CONCURRENCY)
+ .filter_map(std::future::ready)
+ .collect()
+ .await;
+
+ Ok(found)
+ }
+
+ /// Discovers devices in stages, cheapest first: announces this device to
+ /// the network and probes `known_channels` (e.g. the favorites), then
+ /// falls back to scanning the `/24` subnets of the local interface
+ /// addresses `interface_ips`, for networks that do not carry multicast.
+ ///
+ /// The fallback only runs when nothing was confirmed until `grace` after
+ /// the known channels have been probed: any confirmation — a new device
+ /// or a known one — proves that the cheap stages work on this network.
+ ///
+ /// The found devices are put into the store (and emitted) as they answer;
+ /// returns once every stage has finished, including the whole
+ /// announcement burst.
+ pub async fn discover_staged(
+ &self,
+ known_channels: Vec<HttpChannel>,
+ interface_ips: Vec<Ipv4Addr>,
+ port: u16,
+ protocol: ProtocolType,
+ grace: Duration,
+ ) -> Result<(), ClientError> {
+ let confirmations = self.state.confirmations.load(Ordering::Relaxed);
+ let escalate = async {
+ self.discover_known_http_channels(known_channels).await?;
+ tokio::time::sleep(grace).await;
+
+ if self.state.confirmations.load(Ordering::Relaxed) == confirmations {
+ futures_util::future::try_join_all(
+ interface_ips
+ .into_iter()
+ .map(|ip| self.scan_subnet(ip, port, protocol)),
+ )
+ .await?;
+ }
+ Ok(())
+ };
+
+ let (_, escalated) = tokio::join!(self.announce(), escalate);
+ escalated
+ }
+
/// Scans the `/24` subnet of the local interface address `interface_ip`
/// by sending every other host a register request,
/// for networks that do not carry multicast.
@@ -383,6 +458,7 @@ pub async fn start(config: DiscoveryConfig, stop_rx: oneshot::Receiver<()>) -> D
event_tx: config.event_tx,
answering: AtomicBool::new(true),
scanning: std::sync::Mutex::new(HashSet::new()),
+ confirmations: AtomicU64::new(0),
});
// Ends once discovery is stopped: the multicast side then drops its
diff --git a/packages/localsend_isolates/lib/rust/api/discovery.dart b/packages/localsend_isolates/lib/rust/api/discovery.dart
index c800be60..d5a4537b 100644
--- a/packages/localsend_isolates/lib/rust/api/discovery.dart
+++ b/packages/localsend_isolates/lib/rust/api/discovery.dart
@@ -83,13 +83,23 @@ abstract class RsDiscovery implements RustOpaqueInterface {
/// the store's log limit. Empty when the fingerprint is unknown.
Future<List<RsDeviceLog>> deviceLogs({required String fingerprint});
- /// Discovers a device at a known address, e.g. a favorite or a peer that
- /// multicast does not reach, by sending it a register request.
+ /// Discovers devices in stages, cheapest first: announces this device to
+ /// the network and probes [channels] (e.g. the favorites), then falls
+ /// back to scanning the `/24` subnets of the local interface addresses
+ /// [interface_ips], for networks that do not carry multicast. The
+ /// fallback only runs when nothing was confirmed until [grace_ms] after
+ /// the channels have been probed.
///
- /// The confirmed device is also emitted on [RsDiscovery::listen].
- /// Returns `None` when the device did not answer or answered with this
- /// device's own fingerprint (i.e. the device discovered itself).
- Future<RsStoredDevice?> discover({required String host, required int port, required ProtocolType protocol});
+ /// The found devices are emitted on [RsDiscovery::listen] as they answer;
+ /// returns once every stage has finished, including the whole
+ /// announcement burst.
+ Future<void> discoverStaged({
+ required List<RsDeviceChannel> channels,
+ required List<String> interfaceIps,
+ required int port,
+ required ProtocolType protocol,
+ required BigInt graceMs,
+ });
/// Emits a [RsStoredDevice] for every device confirmation until the
/// discovery is stopped. Can only be listened to once.
diff --git a/packages/localsend_isolates/lib/rust/frb_generated.dart b/packages/localsend_isolates/lib/rust/frb_generated.dart
index 6445080c..32d3703d 100644
--- a/packages/localsend_isolates/lib/rust/frb_generated.dart
+++ b/packages/localsend_isolates/lib/rust/frb_generated.dart
@@ -76,7 +76,7 @@ class RustLib extends BaseEntrypoint<RustLibApi, RustLibApiImpl, RustLibWire> {
String get codegenVersion => '2.12.0';
@override
- int get rustContentHash => -324914520;
+ int get rustContentHash => -1979579466;
static const kDefaultExternalLibraryLoaderConfig = ExternalLibraryLoaderConfig(
stem: 'rust_lib_localsend_app',
@@ -120,11 +120,13 @@ abstract class RustLibApi extends BaseApi {
Future<List<RsDeviceLog>> crateApiDiscoveryRsDiscoveryDeviceLogs({required RsDiscovery that, required String fingerprint});
- Future<RsStoredDevice?> crateApiDiscoveryRsDiscoveryDiscover({
+ Future<void> crateApiDiscoveryRsDiscoveryDiscoverStaged({
required RsDiscovery that,
- required String host,
+ required List<RsDeviceChannel> channels,
+ required List<String> interfaceIps,
required int port,
required ProtocolType protocol,
+ required BigInt graceMs,
});
Stream<RsStoredDevice> crateApiDiscoveryRsDiscoveryListen({required RsDiscovery that});
@@ -645,36 +647,40 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
);
@override
- Future<RsStoredDevice?> crateApiDiscoveryRsDiscoveryDiscover({
+ Future<void> crateApiDiscoveryRsDiscoveryDiscoverStaged({
required RsDiscovery that,
- required String host,
+ required List<RsDeviceChannel> channels,
+ required List<String> interfaceIps,
required int port,
required ProtocolType protocol,
+ required BigInt graceMs,
}) {
return handler.executeNormal(
NormalTask(
callFfi: (port_) {
final serializer = SseSerializer(generalizedFrbRustBinding);
sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerRsDiscovery(that, serializer);
- sse_encode_String(host, serializer);
+ sse_encode_list_rs_device_channel(channels, serializer);
+ sse_encode_list_String(interfaceIps, serializer);
sse_encode_u_16(port, serializer);
sse_encode_protocol_type(protocol, serializer);
+ sse_encode_u_64(graceMs, serializer);
pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 10, port: port_);
},
codec: SseCodec(
- decodeSuccessData: sse_decode_opt_box_autoadd_rs_stored_device,
- decodeErrorData: null,
+ decodeSuccessData: sse_decode_unit,
+ decodeErrorData: sse_decode_AnyhowException,
),
- constMeta: kCrateApiDiscoveryRsDiscoveryDiscoverConstMeta,
- argValues: [that, host, port, protocol],
+ constMeta: kCrateApiDiscoveryRsDiscoveryDiscoverStagedConstMeta,
+ argValues: [that, channels, interfaceIps, port, protocol, graceMs],
apiImpl: this,
),
);
}
- TaskConstMeta get kCrateApiDiscoveryRsDiscoveryDiscoverConstMeta => const TaskConstMeta(
- debugName: 'RsDiscovery_discover',
- argNames: ['that', 'host', 'port', 'protocol'],
+ TaskConstMeta get kCrateApiDiscoveryRsDiscoveryDiscoverStagedConstMeta => const TaskConstMeta(
+ debugName: 'RsDiscovery_discover_staged',
+ argNames: ['that', 'channels', 'interfaceIps', 'port', 'protocol', 'graceMs'],
);
@override
@@ -2674,12 +2680,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
return dco_decode_rs_http_client_error(raw);
}
- @protected
- RsStoredDevice dco_decode_box_autoadd_rs_stored_device(dynamic raw) {
- // Codec=Dco (DartCObject based), see doc to use other codecs
- return dco_decode_rs_stored_device(raw);
- }
-
@protected
RTCSendFileResponse dco_decode_box_autoadd_rtc_send_file_response(dynamic raw) {
// Codec=Dco (DartCObject based), see doc to use other codecs
@@ -2935,12 +2935,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
return raw == null ? null : dco_decode_box_autoadd_prepare_upload_response_dto(raw);
}
- @protected
- RsStoredDevice? dco_decode_opt_box_autoadd_rs_stored_device(dynamic raw) {
- // Codec=Dco (DartCObject based), see doc to use other codecs
- return raw == null ? null : dco_decode_box_autoadd_rs_stored_device(raw);
- }
-
@protected
TlsConfig? dco_decode_opt_box_autoadd_tls_config(dynamic raw) {
// Codec=Dco (DartCObject based), see doc to use other codecs
@@ -3969,12 +3963,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
return (sse_decode_rs_http_client_error(deserializer));
}
- @protected
- RsStoredDevice sse_decode_box_autoadd_rs_stored_device(SseDeserializer deserializer) {
- // Codec=Sse (Serialization based), see doc to use other codecs
- return (sse_decode_rs_stored_device(deserializer));
- }
-
@protected
RTCSendFileResponse sse_decode_box_autoadd_rtc_send_file_response(SseDeserializer deserializer) {
// Codec=Sse (Serialization based), see doc to use other codecs
@@ -4307,17 +4295,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
}
}
- @protected
- RsStoredDevice? sse_decode_opt_box_autoadd_rs_stored_device(SseDeserializer deserializer) {
- // Codec=Sse (Serialization based), see doc to use other codecs
-
- if (sse_decode_bool(deserializer)) {
- return (sse_decode_box_autoadd_rs_stored_device(deserializer));
- } else {
- return null;
- }
- }
-
@protected
TlsConfig? sse_decode_opt_box_autoadd_tls_config(SseDeserializer deserializer) {
// Codec=Sse (Serialization based), see doc to use other codecs
@@ -5472,12 +5449,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
sse_encode_rs_http_client_error(self, serializer);
}
- @protected
- void sse_encode_box_autoadd_rs_stored_device(RsStoredDevice self, SseSerializer serializer) {
- // Codec=Sse (Serialization based), see doc to use other codecs
- sse_encode_rs_stored_device(self, serializer);
- }
-
@protected
void sse_encode_box_autoadd_rtc_send_file_response(RTCSendFileResponse self, SseSerializer serializer) {
// Codec=Sse (Serialization based), see doc to use other codecs
@@ -5764,16 +5735,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
}
}
- @protected
- void sse_encode_opt_box_autoadd_rs_stored_device(RsStoredDevice? self, SseSerializer serializer) {
- // Codec=Sse (Serialization based), see doc to use other codecs
-
- sse_encode_bool(self != null, serializer);
- if (self != null) {
- sse_encode_box_autoadd_rs_stored_device(self, serializer);
- }
- }
-
@protected
void sse_encode_opt_box_autoadd_tls_config(TlsConfig? self, SseSerializer serializer) {
// Codec=Sse (Serialization based), see doc to use other codecs
@@ -6402,14 +6363,30 @@ class RsDiscoveryImpl extends RustOpaque implements RsDiscovery {
Future<List<RsDeviceLog>> deviceLogs({required String fingerprint}) =>
RustLib.instance.api.crateApiDiscoveryRsDiscoveryDeviceLogs(that: this, fingerprint: fingerprint);
- /// Discovers a device at a known address, e.g. a favorite or a peer that
- /// multicast does not reach, by sending it a register request.
+ /// Discovers devices in stages, cheapest first: announces this device to
+ /// the network and probes [channels] (e.g. the favorites), then falls
+ /// back to scanning the `/24` subnets of the local interface addresses
+ /// [interface_ips], for networks that do not carry multicast. The
+ /// fallback only runs when nothing was confirmed until [grace_ms] after
+ /// the channels have been probed.
///
- /// The confirmed device is also emitted on [RsDiscovery::listen].
- /// Returns `None` when the device did not answer or answered with this
- /// device's own fingerprint (i.e. the device discovered itself).
- Future<RsStoredDevice?> discover({required String host, required int port, required ProtocolType protocol}) =>
- RustLib.instance.api.crateApiDiscoveryRsDiscoveryDiscover(that: this, host: host, port: port, protocol: protocol);
+ /// The found devices are emitted on [RsDiscovery::listen] as they answer;
+ /// returns once every stage has finished, including the whole
+ /// announcement burst.
+ Future<void> discoverStaged({
+ required List<RsDeviceChannel> channels,
+ required List<String> interfaceIps,
+ required int port,
+ required ProtocolType protocol,
+ required BigInt graceMs,
+ }) => RustLib.instance.api.crateApiDiscoveryRsDiscoveryDiscoverStaged(
+ that: this,
+ channels: channels,
+ interfaceIps: interfaceIps,
+ port: port,
+ protocol: protocol,
+ graceMs: graceMs,
+ );
/// Emits a [RsStoredDevice] for every device confirmation until the
/// discovery is stopped. Can only be listened to once.
diff --git a/packages/localsend_isolates/lib/rust/frb_generated.io.dart b/packages/localsend_isolates/lib/rust/frb_generated.io.dart
index 5e2773fa..04069d0e 100644
--- a/packages/localsend_isolates/lib/rust/frb_generated.io.dart
+++ b/packages/localsend_isolates/lib/rust/frb_generated.io.dart
@@ -274,9 +274,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
RsHttpClientError dco_decode_box_autoadd_rs_http_client_error(dynamic raw);
- @protected
- RsStoredDevice dco_decode_box_autoadd_rs_stored_device(dynamic raw);
-
@protected
RTCSendFileResponse dco_decode_box_autoadd_rtc_send_file_response(dynamic raw);
@@ -383,9 +380,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
PrepareUploadResponseDto? dco_decode_opt_box_autoadd_prepare_upload_response_dto(dynamic raw);
- @protected
- RsStoredDevice? dco_decode_opt_box_autoadd_rs_stored_device(dynamic raw);
-
@protected
TlsConfig? dco_decode_opt_box_autoadd_tls_config(dynamic raw);
@@ -750,9 +744,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
RsHttpClientError sse_decode_box_autoadd_rs_http_client_error(SseDeserializer deserializer);
- @protected
- RsStoredDevice sse_decode_box_autoadd_rs_stored_device(SseDeserializer deserializer);
-
@protected
RTCSendFileResponse sse_decode_box_autoadd_rtc_send_file_response(SseDeserializer deserializer);
@@ -861,9 +852,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
PrepareUploadResponseDto? sse_decode_opt_box_autoadd_prepare_upload_response_dto(SseDeserializer deserializer);
- @protected
- RsStoredDevice? sse_decode_opt_box_autoadd_rs_stored_device(SseDeserializer deserializer);
-
@protected
TlsConfig? sse_decode_opt_box_autoadd_tls_config(SseDeserializer deserializer);
@@ -1273,9 +1261,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
void sse_encode_box_autoadd_rs_http_client_error(RsHttpClientError self, SseSerializer serializer);
- @protected
- void sse_encode_box_autoadd_rs_stored_device(RsStoredDevice self, SseSerializer serializer);
-
@protected
void sse_encode_box_autoadd_rtc_send_file_response(RTCSendFileResponse self, SseSerializer serializer);
@@ -1384,9 +1369,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
void sse_encode_opt_box_autoadd_prepare_upload_response_dto(PrepareUploadResponseDto? self, SseSerializer serializer);
- @protected
- void sse_encode_opt_box_autoadd_rs_stored_device(RsStoredDevice? self, SseSerializer serializer);
-
@protected
void sse_encode_opt_box_autoadd_tls_config(TlsConfig? self, SseSerializer serializer);
diff --git a/packages/localsend_isolates/lib/rust/frb_generated.web.dart b/packages/localsend_isolates/lib/rust/frb_generated.web.dart
index 704605dc..0357d721 100644
--- a/packages/localsend_isolates/lib/rust/frb_generated.web.dart
+++ b/packages/localsend_isolates/lib/rust/frb_generated.web.dart
@@ -276,9 +276,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
RsHttpClientError dco_decode_box_autoadd_rs_http_client_error(dynamic raw);
- @protected
- RsStoredDevice dco_decode_box_autoadd_rs_stored_device(dynamic raw);
-
@protected
RTCSendFileResponse dco_decode_box_autoadd_rtc_send_file_response(dynamic raw);
@@ -385,9 +382,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
PrepareUploadResponseDto? dco_decode_opt_box_autoadd_prepare_upload_response_dto(dynamic raw);
- @protected
- RsStoredDevice? dco_decode_opt_box_autoadd_rs_stored_device(dynamic raw);
-
@protected
TlsConfig? dco_decode_opt_box_autoadd_tls_config(dynamic raw);
@@ -752,9 +746,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
RsHttpClientError sse_decode_box_autoadd_rs_http_client_error(SseDeserializer deserializer);
- @protected
- RsStoredDevice sse_decode_box_autoadd_rs_stored_device(SseDeserializer deserializer);
-
@protected
RTCSendFileResponse sse_decode_box_autoadd_rtc_send_file_response(SseDeserializer deserializer);
@@ -863,9 +854,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
PrepareUploadResponseDto? sse_decode_opt_box_autoadd_prepare_upload_response_dto(SseDeserializer deserializer);
- @protected
- RsStoredDevice? sse_decode_opt_box_autoadd_rs_stored_device(SseDeserializer deserializer);
-
@protected
TlsConfig? sse_decode_opt_box_autoadd_tls_config(SseDeserializer deserializer);
@@ -1275,9 +1263,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
void sse_encode_box_autoadd_rs_http_client_error(RsHttpClientError self, SseSerializer serializer);
- @protected
- void sse_encode_box_autoadd_rs_stored_device(RsStoredDevice self, SseSerializer serializer);
-
@protected
void sse_encode_box_autoadd_rtc_send_file_response(RTCSendFileResponse self, SseSerializer serializer);
@@ -1386,9 +1371,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
void sse_encode_opt_box_autoadd_prepare_upload_response_dto(PrepareUploadResponseDto? self, SseSerializer serializer);
- @protected
- void sse_encode_opt_box_autoadd_rs_stored_device(RsStoredDevice? self, SseSerializer serializer);
-
@protected
void sse_encode_opt_box_autoadd_tls_config(TlsConfig? self, SseSerializer serializer);
diff --git a/packages/localsend_isolates/lib/src/isolate/child/discovery_isolate.dart b/packages/localsend_isolates/lib/src/isolate/child/discovery_isolate.dart
index a611129b..a5725d26 100644
--- a/packages/localsend_isolates/lib/src/isolate/child/discovery_isolate.dart
+++ b/packages/localsend_isolates/lib/src/isolate/child/discovery_isolate.dart
@@ -55,16 +55,24 @@ class DiscoverySubnetScanTask implements DiscoveryTask {
});
}
-/// Probes the known addresses of the favorites over HTTP.
-/// Completes (without events) when every favorite has been probed; the found
+/// Discovers devices in stages, cheapest first: announcement and favorite
+/// probes right away, a subnet scan only when nothing was confirmed within
+/// the grace period.
+/// Completes (without events) when every stage has finished; the found
/// devices arrive on the [DiscoveryListenTask] stream.
-class DiscoveryFavoriteScanTask implements DiscoveryTask {
+class DiscoveryStagedScanTask implements DiscoveryTask {
final List<(String, int)> favorites;
+ final List<String> networkInterfaces;
+ final int port;
final bool https;
+ final Duration grace;
- DiscoveryFavoriteScanTask({
+ DiscoveryStagedScanTask({
required this.favorites,
+ required this.networkInterfaces,
+ required this.port,
required this.https,
+ required this.grace,
});
}
@@ -127,12 +135,15 @@ Future<void> setupDiscoveryIsolate(
https: data.https,
);
break;
- case DiscoveryFavoriteScanTask data:
+ case DiscoveryStagedScanTask data:
await ref
.read(discoveryProvider)
- .discoverFavorites(
- devices: data.favorites,
+ .discoverStaged(
+ favorites: data.favorites,
+ networkInterfaces: data.networkInterfaces,
+ port: data.port,
https: data.https,
+ grace: data.grace,
);
break;
case DiscoveryAddDeviceTask data:
diff --git a/packages/localsend_isolates/lib/src/isolate/parent/actions.dart b/packages/localsend_isolates/lib/src/isolate/parent/actions.dart
index 88ddf727..641d369c 100644
--- a/packages/localsend_isolates/lib/src/isolate/parent/actions.dart
+++ b/packages/localsend_isolates/lib/src/isolate/parent/actions.dart
@@ -71,16 +71,25 @@ class IsolateDiscoverySubnetScanAction extends ReduxActionWithResult<IsolateCont
}
}
-/// Probes the known addresses of the favorites over HTTP.
-/// The returned stream completes (without events) when every favorite has been
-/// probed; the found devices arrive on the [IsolateDiscoveryListenAction] stream.
-class IsolateDiscoveryFavoriteScanAction extends ReduxActionWithResult<IsolateController, ParentIsolateState, Stream<Device>> {
+/// Discovers devices in stages, cheapest first: announcement and favorite
+/// probes right away, a subnet scan only when nothing was confirmed within
+/// the grace period.
+/// The returned stream completes (without events) when every stage has
+/// finished; the found devices arrive on the [IsolateDiscoveryListenAction]
+/// stream.
+class IsolateDiscoveryStagedScanAction extends ReduxActionWithResult<IsolateController, ParentIsolateState, Stream<Device>> {
final List<(String, int)> favorites;
+ final List<String> networkInterfaces;
+ final int port;
final bool https;
+ final Duration grace;
- IsolateDiscoveryFavoriteScanAction({
+ IsolateDiscoveryStagedScanAction({
required this.favorites,
+ required this.networkInterfaces,
+ required this.port,
required this.https,
+ required this.grace,
});
@override
@@ -94,9 +103,12 @@ class IsolateDiscoveryFavoriteScanAction extends ReduxActionWithResult<IsolateCo
state,
connection
.sendWrappedTaskAndListenStream(
- task: DiscoveryFavoriteScanTask(
+ task: DiscoveryStagedScanTask(
favorites: favorites,
+ networkInterfaces: networkInterfaces,
+ port: port,
https: https,
+ grace: grace,
),
)
.toDeviceStream(),
diff --git a/packages/localsend_isolates/lib/src/task/discovery/discovery.dart b/packages/localsend_isolates/lib/src/task/discovery/discovery.dart
index 839af04c..143814dd 100644
--- a/packages/localsend_isolates/lib/src/task/discovery/discovery.dart
+++ b/packages/localsend_isolates/lib/src/task/discovery/discovery.dart
@@ -148,22 +148,38 @@ class DiscoveryService {
);
}
- /// Probes the known addresses of the favorites.
+ /// Discovers devices in stages, cheapest first: announces this device and
+ /// probes the known addresses of the favorites, then falls back to scanning
+ /// the subnets of [networkInterfaces] when nothing was confirmed within the
+ /// grace period.
/// Found devices arrive on the [startListener] stream; this method returns
- /// once every favorite has been probed.
- Future<void> discoverFavorites({required List<(String, int)> devices, required bool https}) async {
+ /// once every stage has finished, including the whole announcement burst.
+ Future<void> discoverStaged({
+ required List<(String, int)> favorites,
+ required List<String> networkInterfaces,
+ required int port,
+ required bool https,
+ required Duration grace,
+ }) async {
final discovery = _discovery;
if (discovery == null) {
- _logger.info('Discovery is not running, skipping favorite scan');
+ _logger.info('Discovery is not running, skipping staged discovery');
return;
}
final protocol = https ? rust_model.ProtocolType.https : rust_model.ProtocolType.http;
- await Future.wait([
- for (final (host, port) in devices) discovery.discover(host: host, port: port, protocol: protocol),
- ]);
+ await discovery.discoverStaged(
+ channels: [
+ for (final (host, port) in favorites) RsDeviceChannel(host: host, port: port, protocol: protocol),
+ ],
+ interfaceIps: networkInterfaces,
+ port: port,
+ protocol: protocol,
+ graceMs: BigInt.from(grace.inMilliseconds),
+ );
}
+
/// The retained confirmations of a stored device, oldest first.
/// Empty when the fingerprint is unknown or the discovery is not running.
Future<List<DeviceLog>> deviceLogs(String fingerprint) async {
diff --git a/packages/localsend_isolates/rust/src/api/discovery.rs b/packages/localsend_isolates/rust/src/api/discovery.rs
index bfeda89c..e1380f21 100644
--- a/packages/localsend_isolates/rust/src/api/discovery.rs
+++ b/packages/localsend_isolates/rust/src/api/discovery.rs
@@ -7,7 +7,6 @@ use localsend::discovery::{
};
use localsend::model::discovery::{DeviceType, ProtocolType};
use localsend::multicast::{DEFAULT_MULTICAST_GROUP_V6, InterfaceFilter, MulticastDevice};
-use localsend::util::error::ErrorChain;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::{Mutex, mpsc, oneshot};
@@ -288,29 +287,51 @@ impl RsDiscovery {
self.instance.handle.set_answer_announcements(answer);
}
- /// Discovers a device at a known address, e.g. a favorite or a peer that
- /// multicast does not reach, by sending it a register request.
+ /// Discovers devices in stages, cheapest first: announces this device to
+ /// the network and probes [channels] (e.g. the favorites), then falls
+ /// back to scanning the `/24` subnets of the local interface addresses
+ /// [interface_ips], for networks that do not carry multicast. The
+ /// fallback only runs when nothing was confirmed until [grace_ms] after
+ /// the channels have been probed.
///
- /// The confirmed device is also emitted on [RsDiscovery::listen].
- /// Returns `None` when the device did not answer or answered with this
- /// device's own fingerprint (i.e. the device discovered itself).
- pub async fn discover(
+ /// The found devices are emitted on [RsDiscovery::listen] as they answer;
+ /// returns once every stage has finished, including the whole
+ /// announcement burst.
+ pub async fn discover_staged(
&self,
- host: String,
+ channels: Vec<RsDeviceChannel>,
+ interface_ips: Vec<String>,
port: u16,
protocol: ProtocolType,
- ) -> Option<RsStoredDevice> {
- match self.instance.handle.discover(&host, port, protocol).await {
- Ok(found) => found.map(rs_stored_device),
- Err(err) => {
- tracing::debug!(
- "Could not discover {}://{host}:{port}: {}",
- protocol.as_str(),
- ErrorChain(&err)
- );
- None
- }
- }
+ grace_ms: u64,
+ ) -> anyhow::Result<()> {
+ let channels = channels
+ .into_iter()
+ .map(|channel| HttpChannel {
+ host: channel.host,
+ port: channel.port,
+ protocol: channel.protocol,
+ })
+ .collect();
+ let interface_ips = interface_ips
+ .into_iter()
+ .map(|ip| {
+ ip.parse()
+ .map_err(|_| anyhow::anyhow!("Invalid interface address: {ip}"))
+ })
+ .collect::<anyhow::Result<Vec<_>>>()?;
+
+ self.instance
+ .handle
+ .discover_staged(
+ channels,
+ interface_ips,
+ port,
+ protocol,
+ Duration::from_millis(grace_ms),
+ )
+ .await?;
+ Ok(())
}
/// Scans the `/24` subnet of the local interface address [interface_ip]
diff --git a/packages/localsend_isolates/rust/src/frb_generated.rs b/packages/localsend_isolates/rust/src/frb_generated.rs
index 4f5cf155..5847ab74 100644
--- a/packages/localsend_isolates/rust/src/frb_generated.rs
+++ b/packages/localsend_isolates/rust/src/frb_generated.rs
@@ -44,7 +44,7 @@ flutter_rust_bridge::frb_generated_boilerplate!(
default_rust_auto_opaque = RustAutoOpaqueMoi,
);
pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_VERSION: &str = "2.12.0";
-pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_CONTENT_HASH: i32 = -324914520;
+pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_CONTENT_HASH: i32 = -1979579466;
// Section: executor
@@ -582,7 +582,7 @@ fn wire__crate__api__discovery__RsDiscovery_device_logs_impl(
},
)
}
-fn wire__crate__api__discovery__RsDiscovery_discover_impl(
+fn wire__crate__api__discovery__RsDiscovery_discover_staged_impl(
port_: flutter_rust_bridge::for_generated::MessagePort,
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
rust_vec_len_: i32,
@@ -590,7 +590,7 @@ fn wire__crate__api__discovery__RsDiscovery_discover_impl(
) {
FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::<flutter_rust_bridge::for_generated::SseCodec, _, _, _>(
flutter_rust_bridge::for_generated::TaskInfo {
- debug_name: "RsDiscovery_discover",
+ debug_name: "RsDiscovery_discover_staged",
port: Some(port_),
mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal,
},
@@ -607,12 +607,15 @@ fn wire__crate__api__discovery__RsDiscovery_discover_impl(
let api_that = <RustOpaqueMoi<
flutter_rust_bridge::for_generated::RustAutoOpaqueInner<RsDiscovery>,
>>::sse_decode(&mut deserializer);
- let api_host = <String>::sse_decode(&mut deserializer);
+ let api_channels =
+ <Vec<crate::api::discovery::RsDeviceChannel>>::sse_decode(&mut deserializer);
+ let api_interface_ips = <Vec<String>>::sse_decode(&mut deserializer);
let api_port = <u16>::sse_decode(&mut deserializer);
let api_protocol = <crate::api::model::ProtocolType>::sse_decode(&mut deserializer);
+ let api_grace_ms = <u64>::sse_decode(&mut deserializer);
deserializer.end();
move |context| async move {
- transform_result_sse::<_, ()>(
+ transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>(
(move || async move {
let mut api_that_guard = None;
let decode_indices_ =
@@ -631,15 +634,15 @@ fn wire__crate__api__discovery__RsDiscovery_discover_impl(
}
}
let api_that_guard = api_that_guard.unwrap();
- let output_ok = Result::<_, ()>::Ok(
- crate::api::discovery::RsDiscovery::discover(
- &*api_that_guard,
- api_host,
- api_port,
- api_protocol,
- )
- .await,
- )?;
+ let output_ok = crate::api::discovery::RsDiscovery::discover_staged(
+ &*api_that_guard,
+ api_channels,
+ api_interface_ips,
+ api_port,
+ api_protocol,
+ api_grace_ms,
+ )
+ .await?;
Ok(output_ok)
})()
.await,
@@ -4336,19 +4339,6 @@ impl SseDecode for Option<crate::api::model::PrepareUploadResponseDto> {
}
}
-impl SseDecode for Option<crate::api::discovery::RsStoredDevice> {
- // Codec=Sse (Serialization based), see doc to use other codecs
- fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
- if (<bool>::sse_decode(deserializer)) {
- return Some(<crate::api::discovery::RsStoredDevice>::sse_decode(
- deserializer,
- ));
- } else {
- return None;
- }
- }
-}
-
impl SseDecode for Option<crate::api::server::TlsConfig> {
// Codec=Sse (Serialization based), see doc to use other codecs
fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
@@ -5166,7 +5156,7 @@ fn pde_ffi_dispatcher_primary_impl(
rust_vec_len,
data_len,
),
- 10 => wire__crate__api__discovery__RsDiscovery_discover_impl(
+ 10 => wire__crate__api__discovery__RsDiscovery_discover_staged_impl(
port,
ptr,
rust_vec_len,
@@ -7218,16 +7208,6 @@ impl SseEncode for Option<crate::api::model::PrepareUploadResponseDto> {
}
}
-impl SseEncode for Option<crate::api::discovery::RsStoredDevice> {
- // Codec=Sse (Serialization based), see doc to use other codecs
- fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
- <bool>::sse_encode(self.is_some(), serializer);
- if let Some(value) = self {
- <crate::api::discovery::RsStoredDevice>::sse_encode(value, serializer);
- }
- }
-}
-
impl SseEncode for Option<crate::api::server::TlsConfig> {
// Codec=Sse (Serialization based), see doc to use other codecs
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {