Repository navigation
Expand file tree
/
Copy pathnode_io.rs
More file actions
1370 lines (1267 loc) · 63.6 KB
/
Copy pathnode_io.rs
File metadata and controls
1370 lines (1267 loc) · 63.6 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
//! Inbound node I/O: read loop, frame decryption, node routing, acks and stream errors.
use super::*;
use wacore::net::DisconnectReason;
/// Non-error exits of [`Client::read_messages_loop`] — `ServerRecycle` keeps the
/// routine reconnect path out of `Err`, so severity consumers (logs, the span's
/// `err(...)` capture, error trackers) only fire for genuine failures.
pub(crate) enum ReadLoopExit {
/// Shutdown signal or an expected disconnect.
Expected,
/// Server ended the stream cleanly (the routine WhatsApp reconnect path).
ServerRecycle(DisconnectReason),
}
/// Genuine failures of [`Client::read_messages_loop`] — everything here is worth
/// reporting loudly, unlike [`ReadLoopExit`].
#[derive(Debug, thiserror::Error)]
pub(crate) enum ReadLoopError {
#[error("cannot start message loop: {0}")]
NotStarted(&'static str),
#[error("transport disconnected: {0}")]
Transport(DisconnectReason),
#[error("transport event channel closed")]
ChannelClosed,
}
impl ReadLoopError {
/// The disconnect reason to surface on the `Disconnected` event; failures
/// that carry none map to `Unknown` (conservative, matches `is_clean_shutdown`).
pub(crate) fn into_reason(self) -> DisconnectReason {
match self {
Self::Transport(reason) => reason,
Self::NotStarted(_) | Self::ChannelClosed => DisconnectReason::Unknown,
}
}
}
impl Client {
/// Read the current semaphore generation and Arc atomically under the mutex.
pub(crate) fn read_message_semaphore(&self) -> (u64, Arc<async_lock::Semaphore>) {
let guard = match self.message_processing_semaphore.lock() {
Ok(g) => g,
Err(poisoned) => poisoned.into_inner(),
};
(
self.message_semaphore_generation.load(Ordering::SeqCst),
guard.clone(),
)
}
/// Replace the message processing semaphore and bump the generation counter.
///
/// Both operations happen under the same mutex hold so readers always see
/// a consistent (generation, Arc) pair. Must be called from a non-async
/// context or inside a scoped block (MutexGuard is !Send).
pub(crate) fn swap_message_semaphore(&self, permits: usize) {
let mut guard = match self.message_processing_semaphore.lock() {
Ok(g) => g,
Err(poisoned) => poisoned.into_inner(),
};
*guard = Arc::new(async_lock::Semaphore::new(permits));
self.message_semaphore_generation
.fetch_add(1, Ordering::SeqCst);
}
/// Acquire one permit from the CURRENT message-processing semaphore.
///
/// The semaphore can be swapped while a waiter sleeps (offline online
/// transition); a permit from the stale semaphore would be a no-op guard,
/// so re-acquire until generation and semaphore agree. Shared by stanza
/// processing and the commit batcher: both must serialize on the same
/// instance for the drain-flush safety argument to hold.
pub(crate) async fn acquire_message_processing_permit(&self) -> async_lock::SemaphoreGuardArc {
loop {
let (generation, semaphore) = self.read_message_semaphore();
let permit = semaphore.acquire_arc().await;
if generation == self.message_semaphore_generation.load(Ordering::SeqCst) {
return permit;
}
// Generation changed while waiting: drop the stale permit and
// retry with the new semaphore.
drop(permit);
}
}
// err(...) stays at the default ERROR on purpose: with the routine server
// recycle moved to Ok(ServerRecycle), an Err from this loop now always means
// something genuinely wrong — so the automatic capture only ever reports
// real failures, not WhatsApp's periodic stream recycling.
#[cfg_attr(
feature = "tracing",
tracing::instrument(
name = "wa.conn.read_loop",
level = "debug",
skip_all,
fields(lid = tracing::field::Empty, pn = tracing::field::Empty),
err(Debug)
)
)]
pub(crate) async fn read_messages_loop(
self: &Arc<Self>,
) -> Result<ReadLoopExit, ReadLoopError> {
#[cfg(feature = "tracing")]
self.record_identity_on_span(&tracing::Span::current());
debug!("Starting message processing loop...");
let mut rx_guard = self.transport_events.lock().await;
let transport_events = rx_guard
.take()
.ok_or(ReadLoopError::NotStarted("not connected"))?;
drop(rx_guard);
// The noise socket is installed before this loop starts (connect_internal)
// and replaced only across reconnects, which tear this loop down first —
// so resolve it once instead of locking the mutex per frame.
let noise_socket = self
.get_noise_socket()
.await
.map_err(|_| ReadLoopError::NotStarted("no noise socket"))?;
// Frame decoder to parse incoming data
let mut frame_decoder = wacore::framing::FrameDecoder::new();
let shutdown = self.connection_shutdown_signal();
// Subscribe once: a fresh wait_for_shutdown() inside the select allocated an
// event_listener on every frame. The signal is one-shot, so a single pinned
// listener still catches an in-loop firing.
let shutdown_fut = wacore::runtime::wait_for_shutdown(&shutdown).fuse();
futures::pin_mut!(shutdown_fut);
loop {
futures::select_biased! {
_ = shutdown_fut => {
debug!("Shutdown signaled in message loop. Exiting message loop.");
return Ok(ReadLoopExit::Expected);
},
event_result = transport_events.recv().fuse() => {
match event_result {
Ok(crate::transport::TransportEvent::DataReceived(data)) => {
// Update dead-socket timer (WA Web: deadSocketTimer reset)
self.stats.mark_recv_activity();
let wire_bytes = data.len();
// Feed data into the frame decoder. The payload is
// adopted zero-copy when it is the sole reference
// and no partial frame is pending (steady state).
frame_decoder.feed_bytes(data);
// Process all complete frames.
// Frame decryption must be sequential (noise protocol counter),
// but we spawn node processing concurrently after decryption.
let mut frames_in_batch: u32 = 0;
while let Some(encrypted_frame) = frame_decoder.decode_frame() {
// Decrypt the frame synchronously (required for noise counter ordering)
if let Some(node) = self.decrypt_frame(&noise_socket, encrypted_frame) {
// Determine processing mode for this node:
// - Critical nodes (success/failure/stream:error): inline, required for state
// - Message nodes: inline, preserves arrival order for per-chat queues
// (MessageHandler just enqueues + ACKs, heavy crypto runs in workers)
// - ib (in-band): inline, ensures offline sync tracking (expected count)
// is set up before offline messages are processed
// - Everything else: spawned concurrently for parallelism
let process_inline = matches!(
node.tag(),
"success" | "failure" | "stream:error" | "message" | "ib"
);
if process_inline {
self.process_decrypted_node(node).await;
} else {
let client = self.clone();
self.runtime.spawn(Box::pin(async move {
client.process_decrypted_node(node).await;
})).detach();
}
}
// Check if we should exit after processing (e.g., after 515 stream error)
if self.expected_disconnect.load(Ordering::Relaxed) {
debug!("Expected disconnect signaled during frame processing. Exiting message loop.");
// The batch (this frame included — its counter
// increment is below) must not vanish from the
// wire counters on this exit path.
self.stats.record_recv_batch(wire_bytes, frames_in_batch + 1);
return Ok(ReadLoopExit::Expected);
}
// Cooperative yield — frequency and behavior are runtime-defined.
frames_in_batch += 1;
if frames_in_batch.is_multiple_of(self.runtime.yield_frequency())
&& let Some(yield_fut) = self.runtime.yield_now()
{
yield_fut.await;
}
}
// Count the batch and refresh the timestamp after
// processing so the keepalive loop sees the batch
// completion time, not just the arrival time. Prevents
// stale reads when a large batch (e.g. offline sync)
// takes seconds to drain.
self.stats.record_recv_batch(wire_bytes, frames_in_batch);
},
Ok(crate::transport::TransportEvent::Disconnected(reason)) => {
if !self.expected_disconnect.load(Ordering::Relaxed) {
// A routine server recycle (clean EOF / normal close) is not
// an error — quiet log, Ok exit. A real transport error stays
// WARN + Err so it's never hidden behind reconnect noise.
if reason.is_clean_shutdown() {
info!("Connection closed by server ({reason}); reconnecting.");
return Ok(ReadLoopExit::ServerRecycle(reason));
}
warn!("Transport disconnected: {reason}; reconnecting.");
return Err(ReadLoopError::Transport(reason));
} else {
debug!("Transport disconnected as expected: {reason}");
return Ok(ReadLoopExit::Expected);
}
}
// Event channel closed (no DisconnectReason available) — the
// transport task ended without reporting why. No reason means we
// can't prove it was a clean recycle, so it stays loud (WARN),
// matching the conservative `Unknown` rule in is_clean_shutdown.
Err(_) => {
if !self.expected_disconnect.load(Ordering::Relaxed) {
warn!("Transport event channel closed; reconnecting.");
return Err(ReadLoopError::ChannelClosed);
} else {
return Ok(ReadLoopExit::Expected);
}
}
Ok(crate::transport::TransportEvent::Connected) => {
// Already handled during handshake, but could be useful for logging
debug!("Transport connected event received");
}
}
}
}
}
}
/// Decrypt a frame and return the parsed node as a zero-copy OwnedNodeRef.
/// This must be called sequentially due to noise protocol counter requirements.
#[cfg_attr(
feature = "tracing",
tracing::instrument(name = "wa.conn.decrypt_frame", level = "trace", skip_all)
)]
pub(crate) fn decrypt_frame(
&self,
noise_socket: &crate::socket::noise_socket::NoiseSocket,
encrypted_frame: bytes::BytesMut,
) -> Option<wacore_binary::OwnedNodeRef> {
let decrypted_payload = match noise_socket.decrypt_frame(encrypted_frame) {
Ok(p) => p,
Err(e) => {
log::error!("Failed to decrypt frame: {e}");
return None;
}
};
let buffer = match wacore_binary::util::unpack_bytes(decrypted_payload) {
Ok(data) => data,
Err(e) => {
log::warn!(target: "Client/Recv", "Failed to decompress frame: {e}");
return None;
}
};
match wacore_binary::OwnedNodeRef::new(buffer) {
Ok(owned) => Some(owned),
Err(e) => {
log::warn!(target: "Client/Recv", "Failed to unmarshal node: {e}");
None
}
}
}
/// Process an already-decrypted node.
/// This can be spawned concurrently since it doesn't depend on noise protocol state.
/// The node is wrapped in Arc to avoid cloning when passing through handlers.
pub(crate) async fn process_decrypted_node(
self: &Arc<Self>,
node: wacore_binary::OwnedNodeRef,
) {
// Wrap in Arc once - all handlers will share this same allocation
let node_arc = Arc::new(node);
self.process_node(node_arc).await;
}
/// Process a node wrapped in Arc. Handlers receive the Arc and can share/store it cheaply.
#[cfg_attr(
feature = "tracing",
tracing::instrument(name = "wa.conn.node", level = "trace", skip_all, fields(tag = %node.get().tag.as_ref()))
)]
pub(crate) async fn process_node(self: &Arc<Self>, node: Arc<wacore_binary::OwnedNodeRef>) {
use wacore::xml::DisplayableNodeRef;
let nr = node.get();
// --- Offline Sync Tracking ---
if nr.tag.as_ref() == "ib" {
// Check for offline_preview child to get expected count
if let Some(preview) = nr.get_optional_child("offline_preview") {
let count: usize = preview
.get_attr("count")
.map(|v| v.as_str())
.and_then(|s| s.parse().ok())
.unwrap_or(0);
if count == 0 {
self.offline_sync_metrics
.active
.store(false, Ordering::Release);
debug!(target: "Client/OfflineSync", "Sync COMPLETED: 0 items.");
} else {
// Use stronger memory ordering for state transitions
self.offline_sync_metrics
.total_messages
.store(count, Ordering::Release);
self.offline_sync_metrics
.processed_messages
.store(0, Ordering::Release);
self.offline_sync_metrics
.active
.store(true, Ordering::Release);
match self.offline_sync_metrics.start_time.lock() {
Ok(mut guard) => *guard = Some(wacore::time::Instant::now()),
Err(poison) => *poison.into_inner() = Some(wacore::time::Instant::now()),
}
debug!(target: "Client/OfflineSync", "Sync STARTED: Expecting {} items.", count);
}
} else if self.offline_sync_metrics.active.load(Ordering::Acquire)
&& nr.get_optional_child("offline").is_some()
{
// Handle end marker: <ib><offline count="N"/> signals sync completion
// Only <ib> with an <offline> child is a real end marker.
// Other <ib> children (thread_metadata, edge_routing, dirty) are NOT end markers.
let processed = self
.offline_sync_metrics
.processed_messages
.load(Ordering::Acquire);
let elapsed = match self.offline_sync_metrics.start_time.lock() {
Ok(guard) => guard.map(|t| t.elapsed()).unwrap_or_default(),
Err(poison) => poison.into_inner().map(|t| t.elapsed()).unwrap_or_default(),
};
debug!(target: "Client/OfflineSync", "Sync COMPLETED: End marker received. Processed {} items in {:.2?}.", processed, elapsed);
self.offline_sync_metrics
.active
.store(false, Ordering::Release);
}
}
// Track progress if active
if self.offline_sync_metrics.active.load(Ordering::Acquire) {
// Check for 'offline' attribute on relevant stanzas
if nr.get_attr("offline").is_some() {
let processed = self
.offline_sync_metrics
.processed_messages
.fetch_add(1, Ordering::Release)
+ 1;
let total = self
.offline_sync_metrics
.total_messages
.load(Ordering::Acquire);
if processed.is_multiple_of(50) || processed == total {
trace!(target: "Client/OfflineSync", "Sync Progress: {}/{}", processed, total);
}
// Drive WA Web pull-batch loop (non-adaptive `$13`): when
// remaining drops to <=C and no batch request is in flight,
// schedule the next one.
let pending = total.saturating_sub(processed);
crate::client::offline_resume::on_offline_stanza_arrived(self, pending);
if processed >= total {
let elapsed = match self.offline_sync_metrics.start_time.lock() {
Ok(guard) => guard.map(|t| t.elapsed()).unwrap_or_default(),
Err(poison) => poison.into_inner().map(|t| t.elapsed()).unwrap_or_default(),
};
debug!(target: "Client/OfflineSync", "Sync COMPLETED: Processed {} items in {:.2?}.", processed, elapsed);
self.offline_sync_metrics
.active
.store(false, Ordering::Release);
}
}
}
// --- End Tracking ---
if nr.tag.as_ref() == "iq"
&& let Some(sync_node) = nr.get_optional_child("sync")
&& let Some(collection_node) = sync_node.get_optional_child("collection")
{
let name = collection_node.attrs().optional_string("name");
let name = name.as_deref().unwrap_or("<unknown>");
debug!(target: "Client/Recv", "Received app state sync response for '{name}' (hiding content).");
} else {
debug!(target: "Client/Recv","{}", DisplayableNodeRef(nr));
}
// Prepare deferred ACK cancellation flag (sent after dispatch unless cancelled)
let mut cancelled = false;
// Emit raw node before any early returns so all decoded stanzas
// (including IQ responses and xmlstreamend) reach external observers
if self.raw_node_forwarding.load(Ordering::Relaxed) {
self.core
.event_bus
.dispatch(Event::RawNode(Arc::clone(&node)));
}
if nr.tag.as_ref() == "xmlstreamend" {
if self.expected_disconnect.load(Ordering::Relaxed) {
debug!("Received <xmlstreamend/>, expected disconnect.");
} else {
// A bare <xmlstreamend/> is the server cleanly ending the stream
// (a recycle). We reconnect, so this is routine, not an error.
info!("Received <xmlstreamend/> (server stream end); reconnecting.");
}
self.notify_connection_shutdown();
return;
}
// Check generic node waiters (zero-cost when none registered)
if self.node_waiter_count.load(Ordering::Acquire) > 0 {
self.resolve_node_waiters(&node);
}
if nr.tag.as_ref() == "iq"
&& let Some(id) = nr.get_attr("id").map(|v| v.as_str())
{
// Single lock acquisition: try to remove the waiter directly.
let waiter = self.response_waiters.lock().await.remove(id.as_ref());
if let Some(waiter) = waiter {
if waiter.send(Arc::clone(&node)).is_err() {
warn!(target: "Client/IQ", "Failed to send IQ response to waiter. Receiver was likely dropped.");
}
return;
}
}
// Dispatch to appropriate handler using the router
// Clone Arc (cheap - just reference count) not the Node itself
if !self
.stanza_router
.dispatch(self.clone(), Arc::clone(&node), &mut cancelled)
.await
{
warn!(
"Received unknown top-level node: {}",
DisplayableNodeRef(nr)
);
}
// Send the deferred ACK if applicable and not cancelled by handler
if self.should_ack(nr) && !cancelled {
self.maybe_deferred_ack(node).await;
}
}
/// Per WA Web (`Handle/MsgSendReceipt.js`), only newsletter `<message>`
/// gets `<ack class="message">` on the success path; DM/group use
/// `<receipt>`. Failure paths (retry/backfill/nack) emit `<ack>` from
/// their dedicated handlers, not via this gate.
///
/// status@broadcast is included as a fallback: drop paths in
/// `process_group_enc_batch` (expired status, missing sender key, generic
/// decrypt error) intentionally skip the delivery receipt to avoid
/// inflating the server-side offline counter for messages we'll never
/// process. Without the transport `<ack>` from this gate, the server
/// would redeliver indefinitely. WA Web emits `<receipt context="status">`
/// in the success path on top of this; the duplicate is tolerated.
pub(crate) fn should_ack(&self, node: &wacore_binary::NodeRef<'_>) -> bool {
let tag = node.tag.as_ref();
if node.get_attr("id").is_none() {
return false;
}
let Some(from) = node.get_attr("from") else {
return false;
};
match tag {
"receipt" | "notification" | "call" => true,
"message" => from
.to_jid()
.is_some_and(|j| j.is_newsletter() || j.is_status_broadcast()),
_ => false,
}
}
/// Possibly send a deferred ack: either immediately or via spawned task.
/// Handlers can cancel by setting `cancelled` to true.
/// Uses Arc<OwnedNodeRef> to avoid cloning when spawning the async task.
async fn maybe_deferred_ack(self: &Arc<Self>, node: Arc<wacore_binary::OwnedNodeRef>) {
if self.synchronous_ack {
if let Err(e) = self.send_ack_for(node.get()).await
&& !e.is_transport_unavailable()
{
warn!("Failed to send ack: {e:?}");
}
} else {
let this = self.clone();
self.runtime
.spawn(Box::pin(async move {
if let Err(e) = this.send_ack_for(node.get()).await
&& !e.is_transport_unavailable()
{
warn!("Failed to send ack: {e:?}");
}
}))
.detach();
}
}
/// Build and send an <ack/> node corresponding to the given stanza.
#[cfg_attr(
feature = "tracing",
tracing::instrument(name = "wa.conn.ack", level = "trace", skip_all, err(Debug))
)]
pub(crate) async fn send_ack_for(
&self,
node: &wacore_binary::NodeRef<'_>,
) -> Result<(), ClientError> {
if self.expected_disconnect.load(Ordering::Relaxed) {
return Ok(());
}
if !self.is_connected() {
return Err(ClientError::NotConnected);
}
let own_pn = self.get_pn();
let buf = match encode_ack_bytes(node, own_pn.as_ref()) {
Ok(Some(buf)) => buf,
Ok(None) => return Ok(()),
Err(e) => {
log::warn!("Failed to encode ack: {e}");
return Ok(());
}
};
self.send_raw_bytes(buf).await
}
/// Send a transport ack so the server stops replaying a stanza from the
/// offline queue. Awaitable so callers can order it after a retry receipt
/// in a single flushed task.
pub(crate) async fn send_transport_ack(&self, info: &crate::types::message::MessageInfo) {
let source = message_ack_source_node(info);
let own_pn = self.get_pn();
match encode_ack_bytes(&source.as_node_ref(), own_pn.as_ref()) {
Ok(Some(buf)) => {
if let Err(e) = self.send_raw_bytes(buf).await
&& !e.is_transport_unavailable()
{
log::warn!("Failed to send transport ack for undecryptable message: {e:?}");
}
}
Ok(None) => {}
Err(e) => log::warn!("Failed to encode transport ack: {e}"),
}
}
/// Spawn [`Self::send_transport_ack`], tracked via `outbound_flush` so
/// `disconnect()` flushes it (issue #571), same as delivery receipts.
pub(crate) fn spawn_message_ack(
self: &Arc<Self>,
info: &Arc<crate::types::message::MessageInfo>,
) {
let client = Arc::clone(self);
let info = Arc::clone(info);
self.outbound_flush.spawn(&*self.runtime, async move {
client.send_transport_ack(&info).await;
});
}
/// Tracked ack encoded from the original node. Use when the stanza carries
/// `recipient` (LID-routed/hosted-companion/peer) since `MessageInfo`
/// drops it on non-self branches and the server needs it for routing.
pub(crate) async fn spawn_node_transport_ack(
self: &Arc<Self>,
node: &wacore_binary::NodeRef<'_>,
) {
let own_pn = self.get_pn();
let buf = match encode_ack_bytes(node, own_pn.as_ref()) {
Ok(Some(b)) => b,
Ok(None) => return,
Err(e) => {
log::warn!("Failed to encode node transport ack: {e}");
return;
}
};
let client = Arc::clone(self);
self.outbound_flush.spawn(&*self.runtime, async move {
if let Err(e) = client.send_raw_bytes(buf).await
&& !e.is_transport_unavailable()
{
log::warn!("Failed to send node transport ack: {e:?}");
}
});
}
#[cfg_attr(
feature = "tracing",
tracing::instrument(name = "wa.conn.success", level = "debug", skip_all)
)]
pub(crate) async fn handle_success(self: &Arc<Self>, node: &wacore_binary::NodeRef<'_>) {
// Skip processing if an expected disconnect is pending (e.g., 515 received).
// This prevents race conditions where a spawned success handler runs after
// cleanup_connection_state has already reset is_logged_in.
if self.expected_disconnect.load(Ordering::Relaxed) {
debug!("Ignoring <success> stanza: expected disconnect pending");
return;
}
// Guard against multiple <success> stanzas (WhatsApp may send more than one during
// routing/reconnection). Only process the first one per connection.
if self.is_logged_in.swap(true, Ordering::SeqCst) {
debug!("Ignoring duplicate <success> stanza (already logged in)");
return;
}
// Increment connection generation to invalidate any stale post-login tasks
// from previous connections (e.g., during 515 reconnect cycles).
let current_generation = self.connection_generation.fetch_add(1, Ordering::SeqCst) + 1;
info!(
"Successfully authenticated with WhatsApp servers! (gen={})",
current_generation
);
// Record the auth time but DON'T reset the backoff counter yet: WA Web
// resets only after the connection has been stable for ~30s
// (`resetDelay`). Resetting on <success> alone lets a server that
// authenticates then immediately drops keep us in a 1s reconnect storm.
// The run loop does the stability-gated reset on the next disconnect.
self.connected_at_ms
.store(wacore::time::now_millis(), Ordering::Relaxed);
// Fresh connection starts un-penalized (see backoff_reset_suppressed).
self.backoff_reset_suppressed
.store(false, Ordering::Relaxed);
self.update_server_time_offset(node);
// Extract LID from the node before spawning (node isn't Send).
let lid_from_server = match node.get_attr("lid") {
Some(lid_value) => match lid_value.to_jid() {
Some(lid) => Some(lid),
None => {
warn!("Failed to parse LID from success stanza: {lid_value}");
None
}
},
None => {
warn!("LID not found in <success> stanza. Group messaging may fail.");
None
}
};
let client_clone = self.clone();
let task_generation = current_generation;
self.runtime.spawn(Box::pin(async move {
// Update LID if changed (moved here to avoid blocking the read loop
// on Device snapshot + write lock).
if let Some(lid) = lid_from_server {
let device_snapshot =
client_clone.persistence_manager.get_device_snapshot();
if device_snapshot.lid.as_ref() != Some(&lid) {
debug!("Updating LID from server to '{}'", lid.observe());
client_clone
.persistence_manager
.process_command(DeviceCommand::SetLid(Some(lid)))
.await;
}
}
// WA Web bumps `lc` after each successful auth (Start/Backend.js
// listener on `onOpenSocketStream`). The Comms `onConnect` handler
// gates the trigger on `isRegistered()`, so the bump only happens
// for already-paired logins — never during the pairing XX
// handshake. We mirror that by skipping when `device.pn` is None.
let already_paired = client_clone
.persistence_manager
.get_device_snapshot()
.pn
.is_some();
if already_paired {
client_clone
.persistence_manager
.process_command(DeviceCommand::IncrementLoginCounter)
.await;
}
// Macro to check if this task is still valid (connection hasn't been replaced)
macro_rules! check_generation {
() => {
if client_clone.connection_generation.load(Ordering::SeqCst) != task_generation
{
debug!("Post-login task cancelled: connection generation changed");
return;
}
};
}
debug!(
"Starting post-login initialization sequence (gen={})...",
task_generation
);
// Check if we need initial app state sync (empty pushname indicates fresh pairing
// where pushname will come from app state sync's setting_pushName mutation)
let device_snapshot = client_clone.persistence_manager.get_device_snapshot();
let needs_pushname_from_sync = device_snapshot.push_name.is_empty();
if needs_pushname_from_sync {
debug!("Push name is empty - will be set from app state sync (setting_pushName)");
}
// Check connection before network operations.
// During pairing, a 515 disconnect happens quickly after success,
// so the socket may already be gone.
if !client_clone.is_connected() {
debug!(
"Skipping post-login init: connection closed (likely pairing phase reconnect)"
);
return;
}
check_generation!();
client_clone.send_unified_session().await;
// === Establish session with primary phone for PDO ===
// This must happen BEFORE we exit passive mode (before offline messages arrive).
// PDO needs a session with device 0 to request decrypted content from our phone.
// Matches WhatsApp Web's bootstrapDeviceCapabilities() pattern.
check_generation!();
if let Err(e) = client_clone
.establish_primary_phone_session_immediate()
.await
{
warn!(target: "Client/PDO", "Failed to establish session with primary phone on login: {:?}", e);
// Don't fail login - PDO will retry via ensure_e2e_sessions fallback
}
check_generation!();
if !client_clone.is_connected() {
debug!("Skipping passive tasks: connection closed");
return;
}
if let Err(e) = client_clone.upload_pre_keys_at_login().await
&& !client_clone.is_shutting_down()
{
warn!("Failed to upload pre-keys during startup: {e:?}");
}
// WA Web RotateKeyJob: rotate the signed pre-key on its cadence.
// Spawned so a slow or failing encrypt IQ never delays the rest of
// post-login init.
check_generation!();
let rotate_client = client_clone.clone();
let rotate_generation = task_generation;
client_clone
.runtime
.spawn(Box::pin(async move {
// A newer connection may have taken over between spawn and now;
// rotating on a stale generation would upload a duplicate key.
if rotate_client.connection_generation.load(Ordering::SeqCst)
!= rotate_generation
{
return;
}
if let Err(e) = rotate_client.maybe_rotate_signed_pre_key().await
&& !rotate_client.is_shutting_down()
{
warn!("Signed pre-key rotation check failed: {e:?}");
}
}))
.detach();
// === Send active IQ ===
// The server sends <ib><offline count="X"/></ib> AFTER we exit passive mode.
// This matches WhatsApp Web's behavior: executePassiveTasks() -> sendPassiveModeProtocol("active")
check_generation!();
if !client_clone.is_connected() {
debug!("Skipping active IQ: connection closed");
return;
}
if let Err(e) = client_clone.set_passive(false).await
&& !client_clone.is_shutting_down()
{
warn!("Failed to send post-connect active IQ: {e:?}");
}
// === Wait for offline sync to complete ===
// The server sends <ib><offline count="X"/></ib> after we exit passive mode.
client_clone.wait_for_offline_delivery_end().await;
// Check if connection was replaced while waiting
check_generation!();
// Re-check connection and generation before sending presence
check_generation!();
if !client_clone.is_connected() {
debug!("Skipping presence: connection closed");
return;
}
// Background initialization queries (can run in parallel, non-blocking)
let bg_client = client_clone.clone();
let bg_generation = task_generation;
client_clone.runtime.spawn(Box::pin(async move {
// Check connection and generation before starting background queries
if bg_client.connection_generation.load(Ordering::SeqCst) != bg_generation {
debug!("Skipping background init queries: connection generation changed");
return;
}
if !bg_client.is_connected() {
debug!("Skipping background init queries: connection closed");
return;
}
debug!(
"Sending background initialization queries (Props, Blocklist, Privacy, Digest, Devices)..."
);
let props_fut = bg_client.fetch_props();
let binding = bg_client.blocking();
let blocklist_fut = binding.get_blocklist();
let privacy_fut = bg_client.fetch_privacy_settings();
let digest_fut = bg_client.validate_digest_key();
// Off the pre-active critical path: WA Web's passive tasks don't
// include an own-device usync (it resolves device lists on demand
// at send time), so syncing here instead of before the active IQ
// starts offline delivery one round-trip sooner.
let device_list_fut = bg_client.sync_own_device_list();
let (r_props, r_block, r_priv, r_digest, r_devices) = futures::join!(
props_fut,
blocklist_fut,
privacy_fut,
digest_fut,
device_list_fut
);
// Suppress warnings if connection closed while queries were in-flight
if !bg_client.is_shutting_down() {
if let Err(e) = r_props {
warn!("Background init: Failed to fetch props: {e:?}");
}
if let Err(e) = r_block {
warn!("Background init: Failed to fetch blocklist: {e:?}");
}
if let Err(e) = r_priv {
warn!("Background init: Failed to fetch privacy settings: {e:?}");
}
if let Err(e) = r_digest {
warn!("Background init: Failed to validate digest key: {e:?}");
}
if let Err(e) = r_devices {
bg_client.log_sync_error("sync own device list", &e);
}
}
// Prune expired tcTokens on connect (matches WhatsApp Web's PrivacyTokenJob)
if let Err(e) = bg_client.tc_token().prune_expired().await
&& !bg_client.is_shutting_down()
{
warn!("Background init: Failed to prune expired tc_tokens: {e:?}");
}
})).detach();
check_generation!();
let flag_set = client_clone.needs_initial_full_sync.load(Ordering::Relaxed);
let needs_initial_sync = flag_set || needs_pushname_from_sync;
if needs_initial_sync {
// === Fresh pairing path ===
// Like WhatsApp Web's syncCriticalData(): await critical collections before
// dispatching Connected, so blocklist/privacy settings are applied first.
debug!(
target: "Client/AppState",
"Starting Initial App State Sync (flag_set={flag_set}, needs_pushname={needs_pushname_from_sync})"
);
if !client_clone
.initial_app_state_keys_received
.load(Ordering::Relaxed)
{
debug!(
target: "Client/AppState",
"Waiting up to 5s for app state keys..."
);
let _ = rt_timeout(
&*client_clone.runtime,
Duration::from_secs(5),
client_clone.initial_keys_synced_notifier.listen(),
)
.await;
// Check if connection was replaced while waiting
check_generation!();
}
// Start the critical sync timeout timer matching WhatsApp Web's
// WAWebSyncBootstrap.$15 (setSyncDCriticalDataSyncTimeout).
// WhatsApp Web uses 180s and calls socketLogout(SyncdTimeout) if
// the critical data hasn't synced by then.
const CRITICAL_SYNC_TIMEOUT_SECS: u64 = 180;
let timeout_client = client_clone.clone();
let timeout_generation = task_generation;
let timeout_rt = client_clone.runtime.clone();
let critical_sync_timeout_handle = timeout_rt.spawn(Box::pin(async move {
timeout_client.runtime.sleep(Duration::from_secs(CRITICAL_SYNC_TIMEOUT_SECS)).await;
// Check generation — if connection was replaced, this timeout is stale
if timeout_client.connection_generation.load(Ordering::SeqCst)
!= timeout_generation
{
return;
}
// Matches WhatsApp Web's $16(): check if SettingPushName was synced.
// If push_name is still empty after 180s, critical sync failed.
let push_name = timeout_client.get_push_name();
if push_name.is_empty() {
warn!(
target: "Client/AppState",
"Critical app state sync timed out after {CRITICAL_SYNC_TIMEOUT_SECS}s \
(push_name not synced). Reconnecting to retry."
);
// WhatsApp Web does socketLogout here which clears device identity.
// We reconnect instead — preserving credentials and keeping the
// run loop active so auto-reconnect can retry the sync.
timeout_client.reconnect_immediately().await;
} else {
debug!(
target: "Client/AppState",
"Critical sync timeout fired but push_name was already synced"
);
}
}));
// Await critical collections via batched IQ before dispatching Connected.
check_generation!();
match client_clone
.sync_collections_batched(vec![
WAPatchName::CriticalBlock,
WAPatchName::CriticalUnblockLow,
])
.await
{
Ok(()) => {
// Critical sync completed — cancel the timeout timer
critical_sync_timeout_handle.abort();
check_generation!();
client_clone
.resubscribe_presence_subscriptions(task_generation)
.await;
check_generation!();
// Dispatch Connected after critical sync completes.
// Presence is NOT sent here — WhatsApp Web sends presence from the
// setting_pushName mutation handler (WAWebPushNameSync), not from
// criticalSyncDone. Our setting_pushName handler already does this.
client_clone.dispatch_connected();
}
Err(e) => {
client_clone.log_sync_error("critical app state sync", &e);
// Don't abort the timeout or dispatch Connected — the sync failed,
// so the timeout watchdog should remain active to force a reconnect
// if needed. Return early to avoid emitting a spurious Connected event.
return;
}
}
// Spawn remaining non-critical collections in background
let sync_client = client_clone.clone();
let sync_generation = task_generation;
client_clone.runtime.spawn(Box::pin(async move {
if sync_client.connection_generation.load(Ordering::SeqCst) != sync_generation {
debug!("App state sync cancelled: connection generation changed");
return;
}
if let Err(e) = sync_client
.sync_collections_batched(vec![
WAPatchName::RegularLow,
WAPatchName::RegularHigh,
WAPatchName::Regular,
])
.await
{
sync_client.log_sync_error("non-critical app state sync", &e);
}
sync_client
.needs_initial_full_sync
.store(false, Ordering::Relaxed);
debug!(target: "Client/AppState", "Initial App State Sync Completed.");
})).detach();
} else {
// === Reconnection path ===