-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathasync_tasks.rs
More file actions
1119 lines (1066 loc) · 44.3 KB
/
Copy pathasync_tasks.rs
File metadata and controls
1119 lines (1066 loc) · 44.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::models::{Order, User};
use crate::settings::load_settings_from_disk;
use crate::settings::Settings;
use crate::ui::helpers::hydrate_app_admin_keys_from_privkey;
use crate::ui::key_handler::EnterKeyContext;
use crate::ui::FormState;
use crate::ui::{
AdminChatUpdate, AppState, ChatAttachment, LnAddressVerifyResult, MessageNotification,
MostroInfoFetchResult, NetworkStatus, OperationResult, OrderChatUpdate, TakeOrderState, UiMode,
};
use crate::util::fatal::request_fatal_restart;
use crate::util::fetch_mostro_instance_info;
use crate::util::listen_for_order_messages;
use crate::util::order_utils::spawn_fetch_scheduler_loops;
use crate::util::{
any_relay_reachable, catch_unwind_request_fatal_restart, connect_client_safely,
hydrate_startup_active_order_dm_state, set_dm_router_cmd_tx,
unsubscribe_dm_listener_subscriptions, OrderDmSubscriptionCmd, StartupDmHydration,
};
use mostro_core::prelude::{Dispute, SmallOrder, Transport};
use nostr_sdk::prelude::{Client, Keys, PublicKey};
use sqlx::SqlitePool;
use std::str::FromStr;
use std::sync::{Arc, Mutex};
use std::{
env, fs,
time::{SystemTime, UNIX_EPOCH},
};
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender};
use tokio::task::JoinHandle;
use zeroize::Zeroizing;
pub struct RuntimeReconnectContext<'a> {
pub app: &'a mut AppState,
pub client: &'a mut Client,
/// In-memory pubkey passed to key handlers; kept in sync with [`Self::current_mostro_pubkey`].
pub mostro_pubkey: &'a mut PublicKey,
pub current_mostro_pubkey: &'a Arc<Mutex<PublicKey>>,
pub pool: &'a SqlitePool,
pub message_listener_handle: &'a mut JoinHandle<()>,
pub message_notification_tx: &'a UnboundedSender<MessageNotification>,
pub orders: Arc<Mutex<Vec<SmallOrder>>>,
pub disputes: Arc<Mutex<Vec<Dispute>>>,
pub order_fetch_task: &'a mut JoinHandle<()>,
pub dispute_fetch_task: &'a mut JoinHandle<()>,
pub dm_subscription_tx: &'a mut UnboundedSender<OrderDmSubscriptionCmd>,
pub settings: &'a Settings,
}
const POISONED_UI_FATAL: &str = "Internal error. Please restart Mostrix.";
/// Shared by runtime reset paths: log fatal, set exit-on-close, show error mode.
fn apply_poisoned_mutex_ui_fatal(app: &mut AppState, user_message: String) {
request_fatal_restart(user_message);
app.fatal_exit_on_close = true;
app.mode = UiMode::operation_result(OperationResult::Error(POISONED_UI_FATAL.to_string()));
}
fn clear_messages_or_fatal(app: &mut AppState) -> Result<(), ()> {
let poison_message = {
let lock_result = app.messages.lock();
match lock_result {
Ok(mut messages) => {
messages.clear();
return Ok(());
}
Err(e) => {
format!(
"Mostrix encountered an internal error (poisoned messages lock: {e}). Please restart the app."
)
}
}
};
apply_poisoned_mutex_ui_fatal(app, poison_message);
Err(())
}
/// Clears `active_order_trade_indices` or applies fatal UI state and returns `Err(())` on poison.
fn clear_active_order_indices_or_fatal(app: &mut AppState) -> Result<(), ()> {
let poison_message = {
let lock_result = app.active_order_trade_indices.lock();
match lock_result {
Ok(mut active) => {
active.clear();
return Ok(());
}
Err(e) => {
format!(
"Mostrix encountered an internal error (poisoned active order indices lock: {e}). Please restart the app."
)
}
}
};
apply_poisoned_mutex_ui_fatal(app, poison_message);
Err(())
}
/// Resets `pending_notifications` to 0 or applies fatal UI state and returns `Err(())` on poison.
fn reset_pending_notifications_or_fatal(app: &mut AppState) -> Result<(), ()> {
let poison_message = {
let lock_result = app.pending_notifications.lock();
match lock_result {
Ok(mut pending) => {
*pending = 0;
return Ok(());
}
Err(e) => {
format!(
"Mostrix encountered an internal error (poisoned pending notifications lock: {e}). Please restart the app."
)
}
}
};
apply_poisoned_mutex_ui_fatal(app, poison_message);
Err(())
}
fn clear_runtime_session_state(app: &mut AppState) {
if clear_messages_or_fatal(app).is_err() {
return;
}
if clear_active_order_indices_or_fatal(app).is_err() {
return;
}
if reset_pending_notifications_or_fatal(app).is_err() {
return;
}
app.selected_message_idx = 0;
app.pending_post_take_operation_result = None;
}
fn clear_runtime_tracking_state_preserve_messages(app: &mut AppState) {
if clear_active_order_indices_or_fatal(app).is_err() {
return;
}
if reset_pending_notifications_or_fatal(app).is_err() {
return;
}
app.selected_message_idx = 0;
app.pending_post_take_operation_result = None;
if let Ok(mut dropped) = app.dropped_user_history_order_ids.lock() {
dropped.clear();
}
}
/// Fetch instance info for `mostro_pubkey`, refresh [`AppState`] transport, and return it for the DM listener.
async fn dm_transport_for_mostro(
client: &Client,
mostro_pubkey: PublicKey,
app: &mut AppState,
log_context: &str,
) -> Transport {
match fetch_mostro_instance_info(client, mostro_pubkey).await {
Ok(info) => {
app.set_mostro_info(info);
app.transport
}
Err(e) => {
log::warn!(
"{log_context}: failed to fetch Mostro instance info: {e}; defaulting to GiftWrap transport"
);
app.set_mostro_info(None);
Transport::default()
}
}
}
/// Abort and respawn the trade DM listener (e.g. after `protocol_version` / transport changes).
#[allow(clippy::too_many_arguments)]
pub async fn respawn_trade_dm_listener(
app: &mut AppState,
client: &Client,
mostro_pubkey: PublicKey,
pool: &SqlitePool,
message_listener_handle: &mut JoinHandle<()>,
message_notification_tx: &UnboundedSender<MessageNotification>,
dm_subscription_tx: &mut UnboundedSender<OrderDmSubscriptionCmd>,
log_context: &str,
) -> Result<(), String> {
message_listener_handle.abort();
// Await the old task before draining subs so it cannot register new ids after take().
let old_listener = std::mem::replace(message_listener_handle, tokio::spawn(async {}));
let _ = old_listener.await;
// DM listener subs only — `Client` is shared with order/dispute fetch schedulers.
unsubscribe_dm_listener_subscriptions(client).await;
let startup_dm_hydration = match hydrate_startup_active_order_dm_state(pool).await {
Ok(h) => h,
Err(e) => {
log::warn!("{log_context}: failed to hydrate startup active order DM state: {e}");
StartupDmHydration::empty()
}
};
if let Ok(mut indices) = app.active_order_trade_indices.lock() {
*indices = startup_dm_hydration.active_order_trade_indices.clone();
}
app.startup_popup_floor_ts = startup_dm_hydration.order_last_seen_dm_ts.clone();
let client_for_messages = client.clone();
let pool_for_messages = pool.clone();
let active_order_trade_indices_clone = Arc::clone(&app.active_order_trade_indices);
let order_last_seen_dm_ts_clone = startup_dm_hydration.order_last_seen_dm_ts.clone();
let messages_clone = Arc::clone(&app.messages);
let message_notification_tx_clone = message_notification_tx.clone();
let pending_notifications_clone = Arc::clone(&app.pending_notifications);
let dropped_user_history_clone = Arc::clone(&app.dropped_user_history_order_ids);
let (new_dm_tx, new_dm_rx) = tokio::sync::mpsc::unbounded_channel::<OrderDmSubscriptionCmd>();
*dm_subscription_tx = new_dm_tx;
set_dm_router_cmd_tx(dm_subscription_tx.clone()).map_err(|msg| msg.to_string())?;
let dm_transport = app.transport;
*message_listener_handle = tokio::spawn(async move {
catch_unwind_request_fatal_restart("trade DM listener", async move {
listen_for_order_messages(
client_for_messages,
mostro_pubkey,
dm_transport,
pool_for_messages,
active_order_trade_indices_clone,
order_last_seen_dm_ts_clone,
messages_clone,
message_notification_tx_clone,
pending_notifications_clone,
dropped_user_history_clone,
new_dm_rx,
)
.await;
})
.await;
});
Ok(())
}
/// Reload Nostr client, Mostro pubkey, and message listener after the user persisted new keys
/// (`pending_key_reload`). Updates `app` and shared runtime state on success; sets an error
/// [`OperationResult`] on failure.
#[allow(clippy::too_many_arguments)]
pub async fn apply_pending_key_reload(
app: &mut AppState,
client: &mut Client,
mostro_pubkey: &mut PublicKey,
current_mostro_pubkey: &Arc<Mutex<PublicKey>>,
pool: &SqlitePool,
message_listener_handle: &mut JoinHandle<()>,
message_notification_tx: &UnboundedSender<MessageNotification>,
orders: Arc<Mutex<Vec<SmallOrder>>>,
disputes: Arc<Mutex<Vec<Dispute>>>,
order_fetch_task: &mut JoinHandle<()>,
dispute_fetch_task: &mut JoinHandle<()>,
dm_subscription_tx: &mut UnboundedSender<OrderDmSubscriptionCmd>,
) {
match load_settings_from_disk() {
Ok(latest_settings) => match latest_settings.nsec_privkey.parse::<Keys>() {
Ok(new_identity_keys) => {
let new_client = Client::new(new_identity_keys);
let mut reload_error: Option<String> = None;
for relay in &latest_settings.relays {
let relay = relay.trim();
if relay.is_empty() {
continue;
}
if let Err(e) = new_client.add_relay(relay).await {
reload_error =
Some(format!("Failed to add relay during key reload: {}", e));
break;
}
}
if let Some(err) = reload_error {
app.pending_key_reload = false;
app.mode = UiMode::operation_result(OperationResult::Error(err));
} else if let Ok(new_mostro_pubkey) =
PublicKey::from_str(&latest_settings.mostro_pubkey)
{
message_listener_handle.abort();
if let Err(e) = connect_client_safely(&new_client).await {
log::warn!("Key reload: failed to connect Nostr client: {e}");
}
*client = new_client;
*mostro_pubkey = new_mostro_pubkey;
match current_mostro_pubkey.lock() {
Ok(mut active_pubkey) => {
*active_pubkey = new_mostro_pubkey;
}
Err(e) => {
request_fatal_restart(format!(
"Mostrix encountered an internal error (poisoned Mostro pubkey lock: {e}). Please restart the app."
));
app.pending_key_reload = false;
app.fatal_exit_on_close = true;
app.mode = UiMode::operation_result(OperationResult::Error(
"Internal error. Please restart Mostrix.".to_string(),
));
return;
}
}
app.currencies_filter = latest_settings.currencies_filter.clone();
hydrate_app_admin_keys_from_privkey(app, &latest_settings.admin_privkey);
clear_runtime_session_state(app);
order_fetch_task.abort();
dispute_fetch_task.abort();
let (o, d) = spawn_fetch_scheduler_loops(
client.clone(),
Arc::clone(current_mostro_pubkey),
Arc::clone(&orders),
Arc::clone(&disputes),
&latest_settings,
pool.clone(),
);
*order_fetch_task = o;
*dispute_fetch_task = d;
let client_for_messages = client.clone();
let pool_for_messages = pool.clone();
let startup_dm_hydration =
match hydrate_startup_active_order_dm_state(pool).await {
Ok(h) => h,
Err(e) => {
log::warn!(
"Key reload: failed to hydrate startup active order DM state: {}",
e
);
StartupDmHydration::empty()
}
};
if let Ok(mut indices) = app.active_order_trade_indices.lock() {
*indices = startup_dm_hydration.active_order_trade_indices.clone();
}
app.startup_popup_floor_ts = startup_dm_hydration.order_last_seen_dm_ts.clone();
let active_order_trade_indices_clone =
Arc::clone(&app.active_order_trade_indices);
let order_last_seen_dm_ts_clone =
startup_dm_hydration.order_last_seen_dm_ts.clone();
let messages_clone = Arc::clone(&app.messages);
let message_notification_tx_clone = message_notification_tx.clone();
let pending_notifications_clone = Arc::clone(&app.pending_notifications);
let dropped_user_history_clone =
Arc::clone(&app.dropped_user_history_order_ids);
let (new_dm_tx, new_dm_rx) =
tokio::sync::mpsc::unbounded_channel::<OrderDmSubscriptionCmd>();
*dm_subscription_tx = new_dm_tx;
let router_reg = set_dm_router_cmd_tx(dm_subscription_tx.clone());
if let Err(msg) = &router_reg {
log::error!("[dm_listener] {}", msg);
}
let dm_mostro_pubkey = new_mostro_pubkey;
let dm_transport =
dm_transport_for_mostro(client, new_mostro_pubkey, app, "Key reload").await;
*message_listener_handle = tokio::spawn(async move {
catch_unwind_request_fatal_restart("trade DM listener", async move {
listen_for_order_messages(
client_for_messages,
dm_mostro_pubkey,
dm_transport,
pool_for_messages,
active_order_trade_indices_clone,
order_last_seen_dm_ts_clone,
messages_clone,
message_notification_tx_clone,
pending_notifications_clone,
dropped_user_history_clone,
new_dm_rx,
)
.await;
})
.await;
});
app.backup_requires_restart = false;
app.pending_key_reload = false;
app.mode = match router_reg {
Ok(()) => UiMode::operation_result(OperationResult::Info(
"Keys reloaded. Active session state has been reset.".to_string(),
)),
Err(msg) => UiMode::operation_result(OperationResult::Error(format!(
"Keys reloaded but DM router registration failed ({msg}). Background trade messages still run; one-shot DM waits may fail until you restart the app."
))),
};
} else {
app.pending_key_reload = false;
app.mode = UiMode::operation_result(OperationResult::Error(format!(
"Invalid Mostro pubkey after key reload: {}",
latest_settings.mostro_pubkey
)));
}
}
Err(e) => {
app.pending_key_reload = false;
app.mode = UiMode::operation_result(OperationResult::Error(format!(
"Invalid identity key after reload: {}",
e
)));
}
},
Err(e) => {
app.pending_key_reload = false;
app.mode = UiMode::operation_result(OperationResult::Error(format!(
"Failed to load settings for key reload: {}",
e
)));
}
}
}
/// Refresh order/dispute relay subscriptions and the trade DM listener from disk settings.
///
/// Lighter than [`apply_pending_key_reload`]: does not rotate identity keys or clear the Messages tab.
/// Used after Mostro pubkey or currency filter changes so live subscriptions match settings.
#[allow(clippy::too_many_arguments)]
pub async fn apply_pending_fetch_scheduler_reload(
app: &mut AppState,
client: &mut Client,
mostro_pubkey: &mut PublicKey,
current_mostro_pubkey: &Arc<Mutex<PublicKey>>,
pool: &SqlitePool,
orders: Arc<Mutex<Vec<SmallOrder>>>,
disputes: Arc<Mutex<Vec<Dispute>>>,
order_fetch_task: &mut JoinHandle<()>,
dispute_fetch_task: &mut JoinHandle<()>,
message_listener_handle: &mut JoinHandle<()>,
message_notification_tx: &UnboundedSender<MessageNotification>,
dm_subscription_tx: &mut UnboundedSender<OrderDmSubscriptionCmd>,
settings_fallback: &Settings,
) -> Result<(), String> {
let latest = match load_settings_from_disk() {
Ok(s) => s,
Err(e) => {
log::warn!(
"Fetch scheduler reload: could not read settings from disk ({e}); using startup snapshot"
);
settings_fallback.clone()
}
};
let new_mostro_pubkey = PublicKey::from_str(&latest.mostro_pubkey).map_err(|e| {
format!(
"Invalid Mostro pubkey in settings ({}): {e}",
latest.mostro_pubkey
)
})?;
message_listener_handle.abort();
order_fetch_task.abort();
dispute_fetch_task.abort();
client.unsubscribe_all().await;
connect_client_safely(client)
.await
.map_err(|e| format!("Fetch scheduler reload: failed to reconnect Nostr client: {e}"))?;
*mostro_pubkey = new_mostro_pubkey;
match current_mostro_pubkey.lock() {
Ok(mut active_pubkey) => {
*active_pubkey = new_mostro_pubkey;
}
Err(e) => {
request_fatal_restart(format!(
"Mostrix encountered an internal error (poisoned Mostro pubkey lock: {e}). Please restart the app."
));
app.fatal_exit_on_close = true;
app.mode = UiMode::operation_result(OperationResult::Error(
"Internal error. Please restart Mostrix.".to_string(),
));
return Err("Internal error. Please restart Mostrix.".to_string());
}
}
app.currencies_filter = latest.currencies_filter.clone();
hydrate_app_admin_keys_from_privkey(app, &latest.admin_privkey);
let (o, d) = spawn_fetch_scheduler_loops(
client.clone(),
Arc::clone(current_mostro_pubkey),
Arc::clone(&orders),
Arc::clone(&disputes),
&latest,
pool.clone(),
);
*order_fetch_task = o;
*dispute_fetch_task = d;
let client_for_messages = client.clone();
let pool_for_messages = pool.clone();
let startup_dm_hydration = match hydrate_startup_active_order_dm_state(pool).await {
Ok(h) => h,
Err(e) => {
log::warn!(
"Fetch scheduler reload: failed to hydrate startup active order DM state: {e}"
);
StartupDmHydration::empty()
}
};
if let Ok(mut indices) = app.active_order_trade_indices.lock() {
*indices = startup_dm_hydration.active_order_trade_indices.clone();
}
app.startup_popup_floor_ts = startup_dm_hydration.order_last_seen_dm_ts.clone();
let active_order_trade_indices_clone = Arc::clone(&app.active_order_trade_indices);
let order_last_seen_dm_ts_clone = startup_dm_hydration.order_last_seen_dm_ts.clone();
let messages_clone = Arc::clone(&app.messages);
let message_notification_tx_clone = message_notification_tx.clone();
let pending_notifications_clone = Arc::clone(&app.pending_notifications);
let dropped_user_history_clone = Arc::clone(&app.dropped_user_history_order_ids);
let (new_dm_tx, new_dm_rx) = tokio::sync::mpsc::unbounded_channel::<OrderDmSubscriptionCmd>();
*dm_subscription_tx = new_dm_tx;
let router_reg = set_dm_router_cmd_tx(dm_subscription_tx.clone());
if let Err(msg) = &router_reg {
log::error!("[dm_listener] {msg}");
}
let dm_mostro_pubkey = new_mostro_pubkey;
let dm_transport =
dm_transport_for_mostro(client, new_mostro_pubkey, app, "Fetch scheduler reload").await;
*message_listener_handle = tokio::spawn(async move {
catch_unwind_request_fatal_restart("trade DM listener", async move {
listen_for_order_messages(
client_for_messages,
dm_mostro_pubkey,
dm_transport,
pool_for_messages,
active_order_trade_indices_clone,
order_last_seen_dm_ts_clone,
messages_clone,
message_notification_tx_clone,
pending_notifications_clone,
dropped_user_history_clone,
new_dm_rx,
)
.await;
})
.await;
});
match router_reg {
Ok(()) => Ok(()),
Err(msg) => Err(format!(
"Subscriptions restarted, but DM router registration failed ({msg}). Consider restarting Mostrix."
)),
}
}
/// Runs [`apply_pending_key_reload`] or [`apply_pending_fetch_scheduler_reload`] when the
/// corresponding [`AppState`] flag is set (key reload takes precedence).
#[allow(clippy::too_many_arguments)]
pub async fn apply_pending_runtime_reloads(
app: &mut AppState,
client: &mut Client,
mostro_pubkey: &mut PublicKey,
current_mostro_pubkey: &Arc<Mutex<PublicKey>>,
pool: &SqlitePool,
message_listener_handle: &mut JoinHandle<()>,
message_notification_tx: &UnboundedSender<MessageNotification>,
orders: &Arc<Mutex<Vec<SmallOrder>>>,
disputes: &Arc<Mutex<Vec<Dispute>>>,
order_fetch_task: &mut JoinHandle<()>,
dispute_fetch_task: &mut JoinHandle<()>,
dm_subscription_tx: &mut UnboundedSender<OrderDmSubscriptionCmd>,
settings_fallback: &Settings,
) {
if app.pending_key_reload {
app.pending_fetch_scheduler_reload = false;
apply_pending_key_reload(
app,
client,
mostro_pubkey,
current_mostro_pubkey,
pool,
message_listener_handle,
message_notification_tx,
Arc::clone(orders),
Arc::clone(disputes),
order_fetch_task,
dispute_fetch_task,
dm_subscription_tx,
)
.await;
} else if app.pending_fetch_scheduler_reload {
match apply_pending_fetch_scheduler_reload(
app,
client,
mostro_pubkey,
current_mostro_pubkey,
pool,
Arc::clone(orders),
Arc::clone(disputes),
order_fetch_task,
dispute_fetch_task,
message_listener_handle,
message_notification_tx,
dm_subscription_tx,
settings_fallback,
)
.await
{
Ok(()) => {
app.pending_fetch_scheduler_reload = false;
}
Err(e) => {
log::warn!("{e}");
// Keep `pending_fetch_scheduler_reload` set so a later tick can retry after relays/connectivity recover.
}
}
}
}
/// Reconnect runtime background tasks after connectivity returns.
///
/// Mirrors the `apply_pending_key_reload` flow (abort/respawn fetch loops and DM listener).
/// Identity keys are unchanged; [`Self::mostro_pubkey`] / [`Self::current_mostro_pubkey`] are
/// refreshed from `settings` so they match disk (e.g. if the Mostro instance pubkey changed).
#[allow(clippy::too_many_arguments)]
pub async fn reload_runtime_session_after_reconnect(
ctx: RuntimeReconnectContext<'_>,
) -> Result<(), String> {
if !any_relay_reachable(&ctx.settings.relays).await {
return Err("No internet / relays unreachable".to_string());
}
ctx.message_listener_handle.abort();
ctx.order_fetch_task.abort();
ctx.dispute_fetch_task.abort();
ctx.client.unsubscribe_all().await;
connect_client_safely(ctx.client)
.await
.map_err(|e| format!("Reconnect: failed to connect Nostr client: {e}"))?;
let new_mostro_pubkey = PublicKey::from_str(&ctx.settings.mostro_pubkey).map_err(|e| {
format!(
"Reconnect: invalid Mostro pubkey in settings ({}): {e}",
ctx.settings.mostro_pubkey
)
})?;
*ctx.mostro_pubkey = new_mostro_pubkey;
match ctx.current_mostro_pubkey.lock() {
Ok(mut active_pubkey) => {
*active_pubkey = new_mostro_pubkey;
}
Err(e) => {
request_fatal_restart(format!(
"Mostrix encountered an internal error (poisoned Mostro pubkey lock: {e}). Please restart the app."
));
return Err("Internal error. Please restart Mostrix.".to_string());
}
}
ctx.app.currencies_filter = ctx.settings.currencies_filter.clone();
hydrate_app_admin_keys_from_privkey(ctx.app, &ctx.settings.admin_privkey);
clear_runtime_tracking_state_preserve_messages(ctx.app);
let (o, d) = spawn_fetch_scheduler_loops(
ctx.client.clone(),
Arc::clone(ctx.current_mostro_pubkey),
Arc::clone(&ctx.orders),
Arc::clone(&ctx.disputes),
ctx.settings,
ctx.pool.clone(),
);
*ctx.order_fetch_task = o;
*ctx.dispute_fetch_task = d;
let client_for_messages = ctx.client.clone();
let pool_for_messages = ctx.pool.clone();
let startup_dm_hydration = match hydrate_startup_active_order_dm_state(ctx.pool).await {
Ok(h) => h,
Err(e) => {
log::warn!(
"Reconnect: failed to hydrate startup active order DM state: {}",
e
);
StartupDmHydration::empty()
}
};
if let Ok(mut indices) = ctx.app.active_order_trade_indices.lock() {
*indices = startup_dm_hydration.active_order_trade_indices.clone();
}
ctx.app.startup_popup_floor_ts = startup_dm_hydration.order_last_seen_dm_ts.clone();
let active_order_trade_indices_clone = Arc::clone(&ctx.app.active_order_trade_indices);
let order_last_seen_dm_ts_clone = startup_dm_hydration.order_last_seen_dm_ts.clone();
let messages_clone = Arc::clone(&ctx.app.messages);
let message_notification_tx_clone = ctx.message_notification_tx.clone();
let pending_notifications_clone = Arc::clone(&ctx.app.pending_notifications);
let dropped_user_history_clone = Arc::clone(&ctx.app.dropped_user_history_order_ids);
let (new_dm_tx, new_dm_rx) = tokio::sync::mpsc::unbounded_channel::<OrderDmSubscriptionCmd>();
*ctx.dm_subscription_tx = new_dm_tx;
let router_reg = set_dm_router_cmd_tx(ctx.dm_subscription_tx.clone());
if let Err(msg) = &router_reg {
log::error!("[dm_listener] {}", msg);
}
let dm_mostro_pubkey = new_mostro_pubkey;
let dm_transport =
dm_transport_for_mostro(ctx.client, new_mostro_pubkey, ctx.app, "Reconnect").await;
*ctx.message_listener_handle = tokio::spawn(async move {
catch_unwind_request_fatal_restart("trade DM listener", async move {
listen_for_order_messages(
client_for_messages,
dm_mostro_pubkey,
dm_transport,
pool_for_messages,
active_order_trade_indices_clone,
order_last_seen_dm_ts_clone,
messages_clone,
message_notification_tx_clone,
pending_notifications_clone,
dropped_user_history_clone,
new_dm_rx,
)
.await;
})
.await;
});
match router_reg {
Ok(()) => Ok(()),
Err(msg) => Err(format!(
"Reconnected, but DM router registration failed ({msg}). Consider restarting Mostrix."
)),
}
}
pub struct AppChannels {
pub order_result_tx: UnboundedSender<OperationResult>,
pub order_result_rx: UnboundedReceiver<OperationResult>,
pub key_rotation_tx: UnboundedSender<Result<Zeroizing<String>, String>>,
pub key_rotation_rx: UnboundedReceiver<Result<Zeroizing<String>, String>>,
pub seed_words_tx: UnboundedSender<Result<Zeroizing<String>, String>>,
pub seed_words_rx: UnboundedReceiver<Result<Zeroizing<String>, String>>,
pub message_notification_tx: UnboundedSender<MessageNotification>,
pub message_notification_rx: UnboundedReceiver<MessageNotification>,
pub admin_chat_updates_tx: UnboundedSender<Result<Vec<AdminChatUpdate>, anyhow::Error>>,
pub admin_chat_updates_rx: UnboundedReceiver<Result<Vec<AdminChatUpdate>, anyhow::Error>>,
pub user_order_chat_updates_tx: UnboundedSender<Result<Vec<OrderChatUpdate>, anyhow::Error>>,
pub user_order_chat_updates_rx: UnboundedReceiver<Result<Vec<OrderChatUpdate>, anyhow::Error>>,
pub save_attachment_tx: UnboundedSender<(String, ChatAttachment)>,
pub save_attachment_rx: UnboundedReceiver<(String, ChatAttachment)>,
pub send_order_attachment_tx: UnboundedSender<crate::util::SendOrderAttachmentJob>,
pub send_order_attachment_rx: UnboundedReceiver<crate::util::SendOrderAttachmentJob>,
pub mostro_info_tx: UnboundedSender<MostroInfoFetchResult>,
pub mostro_info_rx: UnboundedReceiver<MostroInfoFetchResult>,
pub dm_subscription_tx: UnboundedSender<OrderDmSubscriptionCmd>,
pub dm_subscription_rx: UnboundedReceiver<OrderDmSubscriptionCmd>,
pub network_status_tx: UnboundedSender<NetworkStatus>,
pub network_status_rx: UnboundedReceiver<NetworkStatus>,
pub fatal_error_tx: UnboundedSender<String>,
pub fatal_error_rx: UnboundedReceiver<String>,
pub ln_address_result_tx: UnboundedSender<LnAddressVerifyResult>,
pub ln_address_result_rx: UnboundedReceiver<LnAddressVerifyResult>,
}
pub fn create_app_channels() -> AppChannels {
let (order_result_tx, order_result_rx) =
tokio::sync::mpsc::unbounded_channel::<OperationResult>();
let (key_rotation_tx, key_rotation_rx) =
tokio::sync::mpsc::unbounded_channel::<Result<Zeroizing<String>, String>>();
let (seed_words_tx, seed_words_rx) =
tokio::sync::mpsc::unbounded_channel::<Result<Zeroizing<String>, String>>();
let (message_notification_tx, message_notification_rx) =
tokio::sync::mpsc::unbounded_channel::<MessageNotification>();
let (admin_chat_updates_tx, admin_chat_updates_rx) =
tokio::sync::mpsc::unbounded_channel::<Result<Vec<AdminChatUpdate>, anyhow::Error>>();
let (user_order_chat_updates_tx, user_order_chat_updates_rx) =
tokio::sync::mpsc::unbounded_channel::<Result<Vec<OrderChatUpdate>, anyhow::Error>>();
let (save_attachment_tx, save_attachment_rx) =
tokio::sync::mpsc::unbounded_channel::<(String, ChatAttachment)>();
let (send_order_attachment_tx, send_order_attachment_rx) =
tokio::sync::mpsc::unbounded_channel::<crate::util::SendOrderAttachmentJob>();
let (mostro_info_tx, mostro_info_rx) =
tokio::sync::mpsc::unbounded_channel::<MostroInfoFetchResult>();
let (dm_subscription_tx, dm_subscription_rx) =
tokio::sync::mpsc::unbounded_channel::<OrderDmSubscriptionCmd>();
let (network_status_tx, network_status_rx) =
tokio::sync::mpsc::unbounded_channel::<NetworkStatus>();
let (fatal_error_tx, fatal_error_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
let (ln_address_result_tx, ln_address_result_rx) =
tokio::sync::mpsc::unbounded_channel::<LnAddressVerifyResult>();
AppChannels {
order_result_tx,
order_result_rx,
key_rotation_tx,
key_rotation_rx,
seed_words_tx,
seed_words_rx,
message_notification_tx,
message_notification_rx,
admin_chat_updates_tx,
admin_chat_updates_rx,
user_order_chat_updates_tx,
user_order_chat_updates_rx,
save_attachment_tx,
save_attachment_rx,
send_order_attachment_tx,
send_order_attachment_rx,
mostro_info_tx,
mostro_info_rx,
dm_subscription_tx,
dm_subscription_rx,
network_status_tx,
network_status_rx,
fatal_error_tx,
fatal_error_rx,
ln_address_result_tx,
ln_address_result_rx,
}
}
pub fn spawn_send_new_order_task(ctx: &EnterKeyContext<'_>, form: FormState) {
let pool = ctx.pool.clone();
let client = ctx.client.clone();
let order_result_tx = ctx.order_result_tx.clone();
let dm_subscription_tx = ctx.dm_subscription_tx.clone();
let fallback_mostro_pubkey = ctx.mostro_pubkey;
let current_mostro_pubkey = Arc::clone(ctx.current_mostro_pubkey);
let mostro_info = ctx.mostro_info.clone();
tokio::spawn(async move {
let mostro_pubkey = match current_mostro_pubkey.lock() {
Ok(guard) => *guard,
Err(_) => {
log::warn!(
"Failed to lock runtime Mostro pubkey; using settings snapshot (fallback)"
);
fallback_mostro_pubkey
}
};
match crate::util::send_new_order(
&pool,
&client,
mostro_pubkey,
form,
Some(&dm_subscription_tx),
mostro_info.as_ref(),
)
.await
{
Ok(result) => {
let _ = order_result_tx.send(result);
}
Err(e) => {
log::error!("Failed to send order: {}", e);
let _ = order_result_tx.send(OperationResult::Error(e.to_string()));
}
}
});
}
/// Verify LNURL-pay metadata (`tag: payRequest`), then persist trimmed address to `settings.toml`.
pub fn spawn_verify_and_save_ln_address_task(
address: String,
result_tx: UnboundedSender<LnAddressVerifyResult>,
) {
tokio::spawn(async move {
let trimmed = address.trim().to_string();
if trimmed.is_empty() {
let _ = result_tx.send(LnAddressVerifyResult::Err(
"Lightning address cannot be empty".to_string(),
));
return;
}
match crate::util::ln_address::ln_address_pay_request_reachable(&trimmed).await {
Ok(()) => match load_settings_from_disk() {
Ok(mut s) => {
s.ln_address = trimmed.clone();
match crate::settings::save_settings(&s) {
Ok(()) => {
log::info!("Lightning address saved after LNURL verification");
let _ = result_tx.send(LnAddressVerifyResult::Verified {
message: "Lightning address saved (LNURL endpoint verified)."
.to_string(),
});
}
Err(e) => {
let _ = result_tx.send(LnAddressVerifyResult::Err(format!(
"Address verified but failed to save settings: {}",
e
)));
}
}
}
Err(e) => {
let _ = result_tx.send(LnAddressVerifyResult::Err(format!(
"Failed to load settings: {}",
e
)));
}
},
Err(e) => {
let _ = result_tx.send(LnAddressVerifyResult::Err(format!(
"Could not verify Lightning address: {}",
e
)));
}
}
});
}
#[allow(clippy::too_many_arguments)]
pub fn spawn_take_order_task(
pool: SqlitePool,
client: Client,
mostro_pubkey: PublicKey,
take_state: TakeOrderState,
amount: Option<i64>,
invoice: Option<String>,
result_tx: UnboundedSender<OperationResult>,
dm_subscription_tx: UnboundedSender<OrderDmSubscriptionCmd>,
mostro_info: Option<crate::util::MostroInstanceInfo>,
) {
tokio::spawn(async move {
match crate::util::take_order(
&pool,
&client,
mostro_pubkey,
&take_state.order,
amount,
invoice,
Some(&dm_subscription_tx),
mostro_info.as_ref(),
)
.await
{
Ok(result) => {
let _ = result_tx.send(result);
}
Err(e) => {
log::error!("Failed to take order: {}", e);
let _ = result_tx.send(OperationResult::Error(e.to_string()));
}
}
});
}
pub fn spawn_refresh_mostro_info_from_settings_task(
client: Client,
tx: UnboundedSender<MostroInfoFetchResult>,
) {
tokio::spawn(async move {
let settings = match load_settings_from_disk() {
Ok(s) => s,
Err(e) => {
let _ = tx.send(MostroInfoFetchResult::Err(format!(
"Failed to load settings: {}",
e
)));
return;
}
};
let mostro_pubkey = match PublicKey::from_str(&settings.mostro_pubkey) {
Ok(pk) => pk,
Err(e) => {
let _ = tx.send(MostroInfoFetchResult::Err(format!(
"Invalid Mostro pubkey in settings: {}",
e
)));
return;
}
};
let result = fetch_mostro_instance_info(&client, mostro_pubkey).await;
let res = match result {
Ok(Some(info)) => MostroInfoFetchResult::Ok {
info: Box::new(Some(info)),
message: "Mostro instance info refreshed from relays.".to_string(),
},
Ok(None) => MostroInfoFetchResult::Ok {
info: Box::new(None),
message: "No Mostro instance info event found for the current pubkey.".to_string(),
},
Err(e) => {
MostroInfoFetchResult::Err(format!("Failed to refresh Mostro instance info: {}", e))
}
};
let _ = tx.send(res);
});
}
/// `show_result_toast`: when false (e.g. startup), only [`MostroInfoFetchResult::Applied`] is sent on
/// success and errors are logged without UI.
pub fn spawn_refresh_mostro_info_task(
client: Client,
mostro_pubkey: PublicKey,
tx: UnboundedSender<MostroInfoFetchResult>,
show_result_toast: bool,
) {
tokio::spawn(async move {
let result = fetch_mostro_instance_info(&client, mostro_pubkey).await;
if !show_result_toast {
match &result {
Ok(Some(_)) => {}
Ok(None) => {
log::info!("No Mostro instance info event found for current Mostro pubkey");
}
Err(e) => {
log::warn!("Failed to fetch Mostro instance info: {}", e);
}
}
if let Ok(info) = result {
let _ = tx.send(MostroInfoFetchResult::Applied {
info: Box::new(info),
});
}
return;