forked from therealaleph/MasterHttpRelayVPN-RUST
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtunnel_client.rs
More file actions
2266 lines (2107 loc) · 93.1 KB
/
Copy pathtunnel_client.rs
File metadata and controls
2266 lines (2107 loc) · 93.1 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
//! Full-mode tunnel client with pipelined batch multiplexer.
//!
//! A central multiplexer collects pending data from ALL active sessions
//! and fires batch requests without waiting for the previous one to return.
//! Each Apps Script deployment (account) gets its own concurrency pool of
//! 30 in-flight requests — matching the per-account Apps Script limit.
use std::collections::HashMap;
// `AtomicU64` from `std::sync::atomic` requires hardware-backed 64-bit
// atomics, which 32-bit MIPS (`mipsel-unknown-linux-musl` — our OpenWRT
// router target) does not provide — the std type isn't even defined
// there, so the build fails with `no AtomicU64 in sync::atomic`. We
// already pull `portable-atomic` for `domain_fronter.rs` for the same
// reason; reuse it here. `AtomicBool` works fine in std on every target.
use portable_atomic::AtomicU64;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use base64::engine::general_purpose::STANDARD as B64;
use base64::Engine;
use bytes::{Bytes, BytesMut};
use tokio::io::{AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::net::TcpStream;
use tokio::sync::{mpsc, oneshot, Semaphore};
use crate::domain_fronter::{BatchOp, DomainFronter, FronterError, TunnelResponse};
/// Apps Script allows 30 concurrent executions per account / deployment.
const CONCURRENCY_PER_DEPLOYMENT: usize = 30;
/// Maximum total base64-encoded payload bytes in a single batch request.
/// Apps Script accepts up to 50 MB per fetch, but the tunnel-node must
/// parse and fan-out every op — keeping batches under ~4 MB avoids
/// hitting the 6-minute execution cap on the Apps Script side.
const MAX_BATCH_PAYLOAD_BYTES: usize = 4 * 1024 * 1024;
/// Maximum number of ops in a single batch. Prevents one mega-batch from
/// serializing too many sessions behind a single HTTP round-trip.
const MAX_BATCH_OPS: usize = 50;
// Per-batch HTTP round-trip timeout is now read from
// `DomainFronter::batch_timeout()`, sourced from `Config::request_timeout_secs`
// (#430, masterking32 PR #25). The historical default — 30 s, matching Apps
// Script's typical response cliff — lives in `default_request_timeout_secs`
// in `config.rs`.
/// Slack added to the reply-timeout budget on top of `batch_timeout`.
/// Covers spawn/encode overhead and a small margin for clock skew, so
/// the session-side `reply_rx` doesn't fire just before `fire_batch`'s
/// HTTP round-trip would have completed. No retry budget here — each
/// batch makes exactly one attempt (see `fire_batch` docs).
const REPLY_TIMEOUT_SLACK: Duration = Duration::from_secs(5);
/// How long we'll briefly hold the client socket after the local
/// CONNECT/SOCKS5 handshake, waiting for the client's first bytes (the
/// TLS ClientHello for HTTPS). Bundling those bytes with the tunnel-node
/// connect saves one Apps Script round-trip per new flow.
const CLIENT_FIRST_DATA_WAIT: Duration = Duration::from_millis(50);
/// Adaptive coalesce defaults: after each new op arrives, wait another
/// step for more ops. Resets on every arrival, up to max from the first
/// op. Overridable via config `coalesce_step_ms` / `coalesce_max_ms`.
///
/// 200 ms balances latency against batching efficiency. The dominant
/// bottleneck is the Apps Script round-trip (~1.5 s), so the extra
/// 200 ms wait is negligible to the user but lets significantly more
/// ops land in each batch — a page load that would fire 10 separate
/// 1-op batches at 10 ms now packs 3–5 ops per batch, cutting the
/// number of round-trips roughly in half. On idle sessions the step
/// timer fires once with nothing queued (no cost); under load each
/// arriving op resets the timer, so rapid bursts still coalesce up to
/// `DEFAULT_COALESCE_MAX_MS` naturally.
const DEFAULT_COALESCE_STEP_MS: u64 = 200;
const DEFAULT_COALESCE_MAX_MS: u64 = 1000;
/// Structured error code the tunnel-node returns when it doesn't know the
/// op (version mismatch). Must match `tunnel-node/src/main.rs`.
const CODE_UNSUPPORTED_OP: &str = "UNSUPPORTED_OP";
/// Empty poll round-trip latency below which we conclude the tunnel-node
/// is *not* long-polling (legacy fixed-sleep drain instead). On a
/// long-poll-capable server an empty poll with no upstream push either
/// returns near `LONGPOLL_DEADLINE` (~5 s) or comes back early *with*
/// pushed bytes — neither matches a fast empty reply. Threshold sits
/// well above the legacy `~350 ms` drain and well below the long-poll
/// floor, so network jitter on either side won't false-trigger.
const LEGACY_DETECT_THRESHOLD: Duration = Duration::from_millis(1500);
/// How long a deployment stays in "legacy / no long-poll" mode after the
/// last detection. Must be much longer than `LEGACY_DETECT_THRESHOLD` so a
/// freshly-marked deployment doesn't immediately self-recover, but short
/// enough that a redeployed / recovered tunnel-node gets re-probed without
/// requiring a process restart. 60 s lets one stuck deployment widen its
/// own poll cadence without poisoning the others, and self-resets so an
/// upgraded tunnel-node returns to the long-poll fast path on its own.
const LEGACY_RECOVER_AFTER: Duration = Duration::from_secs(60);
/// How long to remember a `Network is unreachable` / `No route to host`
/// failure for a given `(host, port)`. While cached, the proxy short-circuits
/// repeat CONNECTs with an immediate "host unreachable" reply instead of
/// burning a 1.5–2s tunnel batch round-trip on a target that just failed.
/// Real motivator: IPv6-only probe hostnames (e.g. `ds6.probe.*`) on devices
/// without IPv6 — the OS retries the probe every ~1.5s for 10s+, generating
/// 5–10 wasted tunnel sessions per probe.
const UNREACHABLE_CACHE_TTL: Duration = Duration::from_secs(30);
/// Hard cap on negative-cache size. Browsing pulls in dozens of distinct
/// hosts; we don't want a runaway map. Pruned opportunistically on insert.
const UNREACHABLE_CACHE_MAX: usize = 256;
/// Ports where the *server* speaks first (SMTP banner, SSH identification,
/// POP3/IMAP greeting, FTP banner). On these, waiting for client bytes
/// gains nothing and just adds handshake latency — skip the pre-read.
/// HTTP on 80 also qualifies because a naive HTTP client may not flush
/// the request line immediately after the CONNECT reply.
fn is_server_speaks_first(port: u16) -> bool {
matches!(port, 21 | 22 | 25 | 80 | 110 | 143 | 587)
}
/// Recognize the tunnel-node's connect-error strings that mean
/// "this destination is fundamentally unreachable from the tunnel-node's
/// network right now" — distinct from refused/reset/timeout, which can be
/// transient. These come through as the inner `e` of a `TunnelResponse`
/// after the tunnel-node's std::io::Error is stringified, so we match on
/// substrings rather than `ErrorKind`. Linux: errno 101 (ENETUNREACH),
/// errno 113 (EHOSTUNREACH). Format varies a bit across libc/Tokio
/// versions, so cover both the human text and the os-error tag.
fn is_unreachable_error_str(s: &str) -> bool {
let lc = s.to_ascii_lowercase();
lc.contains("network is unreachable")
|| lc.contains("no route to host")
|| lc.contains("os error 101")
|| lc.contains("os error 113")
}
/// Canonicalize a host string for use as a negative-cache key. DNS names
/// are case-insensitive and may carry a trailing root-label dot, so
/// `Example.COM:443`, `example.com:443`, and `example.com.:443` are all the
/// same destination. IPv4 / IPv6 literals are unaffected — IPv4 has no
/// letters, and `Ipv6Addr::to_string()` already emits lowercase.
fn normalize_cache_host(host: &str) -> String {
let trimmed = host.strip_suffix('.').unwrap_or(host);
trimmed.to_ascii_lowercase()
}
// ---------------------------------------------------------------------------
// Multiplexer
// ---------------------------------------------------------------------------
/// Reply payload for ops that go through `fire_batch`. The `String` is the
/// `script_id` of the deployment that processed the batch — needed by
/// `tunnel_loop`'s legacy-detection and per-deployment skip-when-idle
/// decisions, which can't reach `fire_batch`'s local `script_id` any
/// other way. Plain `Connect` doesn't go through `fire_batch` and keeps
/// the simpler reply type.
type BatchedReply = oneshot::Sender<Result<(TunnelResponse, String), String>>;
enum MuxMsg {
Connect {
host: String,
port: u16,
reply: oneshot::Sender<Result<TunnelResponse, String>>,
},
ConnectData {
host: String,
port: u16,
// `Bytes` is internally Arc-backed, so the caller can cheaply
// clone() to keep its own reference for the unsupported-fallback
// replay path without an extra 64 KB copy per session.
data: Bytes,
reply: BatchedReply,
},
Data {
sid: String,
data: Bytes,
reply: BatchedReply,
},
UdpOpen {
host: String,
port: u16,
data: Bytes,
reply: BatchedReply,
},
UdpData {
sid: String,
data: Bytes,
reply: BatchedReply,
},
Close {
sid: String,
},
}
/// Raw, not-yet-encoded form of a batch operation. Lives only inside
/// `mux_loop` and gets converted to `BatchOp` (with base64-encoded `d`)
/// inside `fire_batch`'s spawned task — keeping the encoding work off
/// the single mux thread, which previously had to base64 every op
/// inline before it could move on to the next message.
struct PendingOp {
op: &'static str,
sid: Option<String>,
host: Option<String>,
port: Option<u16>,
/// Raw payload. `None` for empty polls / opless ops; `Some` even
/// when empty preserves the connect_data shape (always emits `d`).
data: Option<Bytes>,
/// True for ops that must serialize `d` even when empty (currently
/// only `connect_data`, which uses presence of `d` as the signal
/// that the caller is opting into the bundled-first-bytes flow).
encode_empty: bool,
}
pub struct TunnelMux {
tx: mpsc::Sender<MuxMsg>,
/// Set to `true` after the first time the tunnel-node rejects
/// `connect_data` as unsupported. Subsequent sessions skip the
/// optimistic path entirely and go straight to plain connect + data.
connect_data_unsupported: Arc<AtomicBool>,
/// Per-deployment legacy state: `script_id` → time it was last
/// observed serving an empty poll faster than `LEGACY_DETECT_THRESHOLD`.
/// Absence means "long-poll capable, or untested." Entries expire after
/// `LEGACY_RECOVER_AFTER` so a redeployed / recovered tunnel-node
/// rejoins the long-poll fast path without requiring a process restart.
///
/// Note: the per-deployment marks here do *not* drive a per-deployment
/// poll cadence — the `tunnel_loop` cadence (read-timeout backoff and
/// skip-empty-when-idle) is gated on the aggregate `all_legacy`,
/// because the next op's deployment is chosen later by
/// `next_script_id()` round-robin and the loop can't pre-select. What
/// the per-deployment design *does* fix vs the old single AtomicBool:
/// * one slow / legacy deployment can no longer flip the aggregate
/// true on its own — every deployment has to be marked first;
/// * deployments recover individually on the TTL, so an upgraded
/// tunnel-node lifts the aggregate without needing the others to
/// also recover or the process to restart;
/// * the warn log fires once per (deployment, recovery cycle), so
/// re-detection after recovery is a real signal in the logs.
/// The cost: legacy deployments still receive fast empty polls in
/// mixed mode (round-robin doesn't know to avoid them). Worth it to
/// keep pushed bytes flowing through the long-poll-capable peers.
legacy_deployments: Mutex<HashMap<String, Instant>>,
/// Lock-free hot-path snapshot of "every known deployment is currently
/// in legacy mode." Recomputed under `legacy_deployments`'s mutex on
/// every mark/expire and read with a relaxed load from `tunnel_loop`.
/// True only when this process has fast-empty observations for *all*
/// `num_scripts` deployments simultaneously — that's when the per-
/// session 30 s read-timeout backoff (the only setting where there is
/// no per-deployment alternative) is still appropriate. Invariant: the
/// atomic is always written *after* the map insert, under the same
/// lock, so any reader that sees `true` was preceded by a complete
/// map update.
all_legacy: Arc<AtomicBool>,
/// Count of *unique* configured deployment IDs at start time.
/// Snapshotted from `fronter.script_id_list()` deduped, since the
/// aggregate gate compares this against `legacy_deployments.len()`
/// (a HashMap, so unique-keyed) — using the raw configured count
/// would make the gate unreachable whenever a user lists the same
/// script_id twice. Blacklisted-but-configured deployments still
/// count here; see `all_servers_legacy` for why.
num_scripts: usize,
/// Pre-read observability. Lets an operator see whether the 50 ms
/// wait-for-first-bytes is pulling its weight:
/// * `preread_win` — client sent bytes in time, bundled with connect
/// * `preread_loss` — timed out empty; paid 50 ms for nothing
/// * `preread_skip_port` — port was server-speaks-first; skipped wait
/// * `preread_skip_unsupported` — tunnel-node said no; skipped wait
/// A rolling sum of win-time (µs) drives a `mean_win_time` readout so
/// you can tune `CLIENT_FIRST_DATA_WAIT` against real client flush
/// timing. A summary line is logged every 100 preread events.
preread_win: AtomicU64,
preread_loss: AtomicU64,
preread_skip_port: AtomicU64,
preread_skip_unsupported: AtomicU64,
preread_win_total_us: AtomicU64,
/// Separate monotonic counter used only to trigger the summary log
/// (avoids a race where two threads both see `total % 100 == 0`).
preread_total_events: AtomicU64,
/// Short-lived negative cache for targets the tunnel-node reported as
/// unreachable (`Network is unreachable` / `No route to host`). Keyed by
/// `(host, port)`, value is the expiry instant. Plain Mutex<HashMap> is
/// fine: it's touched once per CONNECT (cheap) and once per failure.
unreachable_cache: Mutex<HashMap<(String, u16), Instant>>,
/// How long a session waits for its batch reply before giving up and
/// retry-polling on the next tick. Computed at construction from
/// `fronter.batch_timeout() + REPLY_TIMEOUT_SLACK` so the session-
/// side `reply_rx` always outlives `fire_batch`'s single HTTP
/// round-trip. Without runtime derivation, an operator who raises
/// `request_timeout_secs` would see sessions abandon replies just
/// before the batch would have completed.
reply_timeout: Duration,
}
impl TunnelMux {
pub fn start(fronter: Arc<DomainFronter>, coalesce_step_ms: u64, coalesce_max_ms: u64) -> Arc<Self> {
// Dedupe before snapshotting: the aggregate `all_legacy` gate
// compares `legacy_deployments.len()` (a HashMap, so unique
// keys) against this count, so using the raw `num_scripts()`
// would make the gate unreachable whenever a user lists the
// same script_id twice in config.
let unique: std::collections::HashSet<&str> = fronter
.script_id_list()
.iter()
.map(String::as_str)
.collect();
let unique_n = unique.len();
let raw_n = fronter.num_scripts();
if unique_n != raw_n {
tracing::warn!(
"tunnel mux: {} deployments configured but only {} unique script_id(s) — duplicate entries ignored for legacy detection",
raw_n,
unique_n,
);
}
tracing::info!(
"tunnel mux: {} deployment(s), {} concurrent per deployment",
unique_n,
CONCURRENCY_PER_DEPLOYMENT
);
let step = if coalesce_step_ms > 0 { coalesce_step_ms } else { DEFAULT_COALESCE_STEP_MS };
let max = if coalesce_max_ms > 0 { coalesce_max_ms } else { DEFAULT_COALESCE_MAX_MS };
tracing::info!("batch coalesce: step={}ms max={}ms", step, max);
// Reply timeout co-varies with `request_timeout_secs` so an
// operator who raises the batch budget doesn't have sessions
// abandoning replies just before the HTTP round-trip would
// have completed. See the `reply_timeout` field comment for
// the invariant.
let reply_timeout = fronter
.batch_timeout()
.saturating_add(REPLY_TIMEOUT_SLACK);
let (tx, rx) = mpsc::channel(512);
tokio::spawn(mux_loop(rx, fronter, step, max));
Arc::new(Self {
tx,
connect_data_unsupported: Arc::new(AtomicBool::new(false)),
legacy_deployments: Mutex::new(HashMap::new()),
all_legacy: Arc::new(AtomicBool::new(false)),
num_scripts: unique_n,
preread_win: AtomicU64::new(0),
preread_loss: AtomicU64::new(0),
preread_skip_port: AtomicU64::new(0),
preread_skip_unsupported: AtomicU64::new(0),
preread_win_total_us: AtomicU64::new(0),
preread_total_events: AtomicU64::new(0),
unreachable_cache: Mutex::new(HashMap::new()),
reply_timeout,
})
}
/// How long a session waits for its batch reply before retry-polling.
/// Co-varies with `Config::request_timeout_secs` so `fire_batch`'s
/// single HTTP round-trip is always covered.
pub fn reply_timeout(&self) -> Duration {
self.reply_timeout
}
async fn send(&self, msg: MuxMsg) {
let _ = self.tx.send(msg).await;
}
pub async fn udp_open(
&self,
host: &str,
port: u16,
data: impl Into<Bytes>,
) -> Result<TunnelResponse, String> {
let (reply_tx, reply_rx) = oneshot::channel();
self.send(MuxMsg::UdpOpen {
host: host.to_string(),
port,
data: data.into(),
reply: reply_tx,
})
.await;
match reply_rx.await {
Ok(Ok((resp, _script_id))) => Ok(resp),
Ok(Err(e)) => Err(e),
Err(_) => Err("mux channel closed".into()),
}
}
pub async fn udp_data(
&self,
sid: &str,
data: impl Into<Bytes>,
) -> Result<TunnelResponse, String> {
let (reply_tx, reply_rx) = oneshot::channel();
self.send(MuxMsg::UdpData {
sid: sid.to_string(),
data: data.into(),
reply: reply_tx,
})
.await;
match reply_rx.await {
Ok(Ok((resp, _script_id))) => Ok(resp),
Ok(Err(e)) => Err(e),
Err(_) => Err("mux channel closed".into()),
}
}
pub async fn close_session(&self, sid: &str) {
self.send(MuxMsg::Close {
sid: sid.to_string(),
})
.await;
}
fn connect_data_unsupported(&self) -> bool {
self.connect_data_unsupported.load(Ordering::Relaxed)
}
fn mark_connect_data_unsupported(&self) {
if !self.connect_data_unsupported.swap(true, Ordering::Relaxed) {
tracing::warn!(
"tunnel-node doesn't support connect_data (pre-v1.x); falling back to plain connect + data for all future sessions"
);
}
}
/// True only when *every* known deployment is currently in legacy
/// mode. Both per-session decisions in `tunnel_loop` (the 30 s
/// read-timeout backoff and the skip-empty-when-idle short-circuit)
/// gate on this aggregate — they can't pick a per-deployment answer
/// ahead of time because the next op's deployment is chosen by
/// `next_script_id()` only when the batch fires. With one
/// long-poll-capable peer still around, the loop must keep emitting
/// empty polls so round-robin lands some on that peer (where the
/// server can hold them open and deliver pushed bytes).
///
/// Known limitation: the comparison is against *all configured*
/// deployments (`num_scripts`), not currently-selectable ones. A
/// fleet where most deployments are blacklisted in `DomainFronter`
/// (10 min cooldown) and the only selectable deployment(s) are
/// legacy will keep the fast cadence for up to that cooldown, even
/// though every reachable peer is legacy. Accepted because
/// integrating the blacklist would require a hot-path query on the
/// fronter's mutex once per `tunnel_loop` iteration; a heavily-
/// blacklisted fleet has bigger problems than quota optimization,
/// and the worst-case quota cost is bounded by the cooldown.
///
/// Hot path: lock-free relaxed load. If the cached value is `true`,
/// double-check under the mutex with a sweep for expired entries —
/// otherwise stale legacy marks would keep us in the slow path forever
/// after every deployment recovers (the `mark_server_no_longpoll` sweep
/// only fires on the next mark, which may never come).
fn all_servers_legacy(&self) -> bool {
if !self.all_legacy.load(Ordering::Relaxed) {
return false;
}
let now = Instant::now();
let mut deps = match self.legacy_deployments.lock() {
Ok(g) => g,
Err(p) => p.into_inner(),
};
deps.retain(|_, marked_at| now.duration_since(*marked_at) < LEGACY_RECOVER_AFTER);
let still_all = deps.len() == self.num_scripts;
if !still_all {
self.all_legacy.store(false, Ordering::Relaxed);
}
still_all
}
fn mark_server_no_longpoll(&self, script_id: &str) {
let now = Instant::now();
let mut deps = match self.legacy_deployments.lock() {
Ok(g) => g,
Err(p) => p.into_inner(),
};
// Inline expiry sweep: if any entry has aged past
// LEGACY_RECOVER_AFTER, drop it before recomputing `all_legacy`.
// Without this, an entry that should have recovered would still
// count toward the aggregate.
deps.retain(|_, marked_at| now.duration_since(*marked_at) < LEGACY_RECOVER_AFTER);
let was_present = deps.contains_key(script_id);
deps.insert(script_id.to_string(), now);
let all = deps.len() == self.num_scripts;
// Atomic written under the lock and *after* the map insert. Any
// reader that observes `all_legacy = true` has seen a complete
// map state where every deployment is marked.
self.all_legacy.store(all, Ordering::Relaxed);
drop(deps);
// Only log on first-mark-for-this-cycle: after `LEGACY_RECOVER_AFTER`
// expiry + re-detection we re-log, which is intentional — that's
// a real signal that the deployment regressed back to legacy mode.
if !was_present {
let short = &script_id[..script_id.len().min(8)];
tracing::warn!(
"tunnel-node deployment {}... returned an empty poll faster than {:?}; assuming legacy (no long-poll) drain — this deployment will skip empty polls when idle for the next {:?}",
short,
LEGACY_DETECT_THRESHOLD,
LEGACY_RECOVER_AFTER,
);
}
}
/// Returns true if `(host, port)` has a non-expired unreachable entry.
/// The proxy front-end uses this to skip the tunnel and reply
/// "host unreachable" immediately on follow-up CONNECTs.
pub fn is_unreachable(&self, host: &str, port: u16) -> bool {
let now = Instant::now();
let mut cache = match self.unreachable_cache.lock() {
Ok(g) => g,
Err(p) => p.into_inner(),
};
let key = (normalize_cache_host(host), port);
match cache.get(&key) {
Some(expiry) if *expiry > now => true,
Some(_) => {
cache.remove(&key);
false
}
None => false,
}
}
/// If `err` looks like a network-unreachable / no-route-to-host error
/// from the tunnel-node, remember the target for `UNREACHABLE_CACHE_TTL`.
/// No-op for any other error (timeouts, refused, EOF, etc.) — those can
/// be transient and we don't want to lock out a host on a flaky moment.
fn record_unreachable_if_match(&self, host: &str, port: u16, err: &str) {
if !is_unreachable_error_str(err) {
return;
}
let mut cache = match self.unreachable_cache.lock() {
Ok(g) => g,
Err(p) => p.into_inner(),
};
// Cap enforcement is two-stage: first drop anything already expired,
// then if we're STILL at/above the cap (i.e. an unbounded burst of
// unique unreachable hosts within the TTL), evict the entry that
// would expire soonest. This bounds the map size at all times — a
// pure `retain` on expiry alone would let the map grow unbounded
// until the first entry's TTL elapses.
if cache.len() >= UNREACHABLE_CACHE_MAX {
let now = Instant::now();
cache.retain(|_, expiry| *expiry > now);
while cache.len() >= UNREACHABLE_CACHE_MAX {
let victim = cache
.iter()
.min_by_key(|(_, expiry)| **expiry)
.map(|(k, _)| k.clone());
match victim {
Some(k) => {
cache.remove(&k);
}
None => break,
}
}
}
let key = (normalize_cache_host(host), port);
cache.insert(key, Instant::now() + UNREACHABLE_CACHE_TTL);
tracing::debug!(
"negative-cached {}:{} for {:?} ({})",
host,
port,
UNREACHABLE_CACHE_TTL,
err
);
}
fn record_preread_win(&self, port: u16, elapsed: Duration) {
self.preread_win.fetch_add(1, Ordering::Relaxed);
self.preread_win_total_us
.fetch_add(elapsed.as_micros() as u64, Ordering::Relaxed);
tracing::debug!("preread win: port={} took={:?}", port, elapsed);
self.maybe_log_preread_summary();
}
fn record_preread_loss(&self, port: u16) {
self.preread_loss.fetch_add(1, Ordering::Relaxed);
tracing::debug!(
"preread loss: port={} (empty within {:?})",
port,
CLIENT_FIRST_DATA_WAIT
);
self.maybe_log_preread_summary();
}
fn record_preread_skip_port(&self, port: u16) {
self.preread_skip_port.fetch_add(1, Ordering::Relaxed);
tracing::debug!("preread skip: port={} (server-speaks-first)", port);
self.maybe_log_preread_summary();
}
fn record_preread_skip_unsupported(&self, port: u16) {
self.preread_skip_unsupported
.fetch_add(1, Ordering::Relaxed);
tracing::debug!("preread skip: port={} (connect_data unsupported)", port);
self.maybe_log_preread_summary();
}
/// Emit an aggregate summary exactly once per 100 preread events.
/// Using a dedicated counter for the trigger avoids a race where two
/// threads both observe the win/loss/skip totals summing to a
/// multiple of 100 — here, exactly one thread gets the boundary.
fn maybe_log_preread_summary(&self) {
let new_count = self.preread_total_events.fetch_add(1, Ordering::Relaxed) + 1;
if new_count % 100 != 0 {
return;
}
let win = self.preread_win.load(Ordering::Relaxed);
let loss = self.preread_loss.load(Ordering::Relaxed);
let skip_port = self.preread_skip_port.load(Ordering::Relaxed);
let skip_unsup = self.preread_skip_unsupported.load(Ordering::Relaxed);
let total_us = self.preread_win_total_us.load(Ordering::Relaxed);
let mean_us = if win > 0 { total_us / win } else { 0 };
tracing::info!(
"connect_data preread: {} win / {} loss / {} skip(port) / {} skip(unsup), mean win time {}µs (ceiling {}µs)",
win,
loss,
skip_port,
skip_unsup,
mean_us,
CLIENT_FIRST_DATA_WAIT.as_micros(),
);
}
}
async fn mux_loop(mut rx: mpsc::Receiver<MuxMsg>, fronter: Arc<DomainFronter>, coalesce_step_ms: u64, coalesce_max_ms: u64) {
let coalesce_step = Duration::from_millis(coalesce_step_ms);
let coalesce_max = Duration::from_millis(coalesce_max_ms);
// One semaphore per deployment ID, each allowing 30 concurrent requests.
let sems: Arc<HashMap<String, Arc<Semaphore>>> = Arc::new(
fronter
.script_id_list()
.iter()
.map(|id| {
(
id.clone(),
Arc::new(Semaphore::new(CONCURRENCY_PER_DEPLOYMENT)),
)
})
.collect(),
);
loop {
let mut msgs = Vec::new();
// Block on the first message — no point waking up to find an empty
// queue. Once the first op lands, the adaptive coalesce loop waits
// in `coalesce_step` increments (resetting on each new arrival, up
// to `coalesce_max`) so concurrent ops land in the same batch.
match rx.recv().await {
Some(msg) => msgs.push(msg),
None => break,
}
let hard_deadline = tokio::time::Instant::now() + coalesce_max;
let mut soft_deadline = tokio::time::Instant::now() + coalesce_step;
loop {
// Drain anything that's already queued without waiting.
while let Ok(msg) = rx.try_recv() {
msgs.push(msg);
// Reset the soft deadline — more ops are arriving.
soft_deadline = tokio::time::Instant::now() + coalesce_step;
}
let now = tokio::time::Instant::now();
let wait_until = soft_deadline.min(hard_deadline);
if now >= wait_until {
break;
}
match tokio::time::timeout(wait_until - now, rx.recv()).await {
Ok(Some(msg)) => {
msgs.push(msg);
// New op arrived — extend the soft deadline.
soft_deadline = tokio::time::Instant::now() + coalesce_step;
}
Ok(None) => return,
Err(_) => break, // soft or hard deadline hit, no more ops
}
}
// Split: plain connects go parallel, data-bearing ops get batched.
let mut accum = BatchAccum::new();
let mut close_sids: Vec<String> = Vec::new();
for msg in msgs {
match msg {
MuxMsg::Connect { host, port, reply } => {
let f = fronter.clone();
tokio::spawn(async move {
let result = f
.tunnel_request("connect", Some(&host), Some(port), None, None)
.await;
match result {
Ok(resp) => {
let _ = reply.send(Ok(resp));
}
Err(e) => {
let _ = reply.send(Err(format!("{}", e)));
}
}
});
}
MuxMsg::ConnectData {
host,
port,
data,
reply,
} => {
let op_bytes = encoded_len(data.len());
let op = PendingOp {
op: "connect_data",
sid: None,
host: Some(host),
port: Some(port),
data: Some(data),
encode_empty: true,
};
accum.push_or_fire(op, op_bytes, reply, &sems, &fronter).await;
}
MuxMsg::Data { sid, data, reply } => {
let op_bytes = encoded_len(data.len());
let op = PendingOp {
op: "data",
sid: Some(sid),
host: None,
port: None,
data: if data.is_empty() { None } else { Some(data) },
encode_empty: false,
};
accum.push_or_fire(op, op_bytes, reply, &sems, &fronter).await;
}
MuxMsg::UdpOpen {
host,
port,
data,
reply,
} => {
let op_bytes = encoded_len(data.len());
let op = PendingOp {
op: "udp_open",
sid: None,
host: Some(host),
port: Some(port),
data: if data.is_empty() { None } else { Some(data) },
encode_empty: false,
};
accum.push_or_fire(op, op_bytes, reply, &sems, &fronter).await;
}
MuxMsg::UdpData { sid, data, reply } => {
let op_bytes = encoded_len(data.len());
let op = PendingOp {
op: "udp_data",
sid: Some(sid),
host: None,
port: None,
data: if data.is_empty() { None } else { Some(data) },
encode_empty: false,
};
accum.push_or_fire(op, op_bytes, reply, &sems, &fronter).await;
}
MuxMsg::Close { sid } => {
close_sids.push(sid);
}
}
}
// `close` ops piggyback on whatever batch we're about to fire — no
// reply channel, no payload, just tell tunnel-node to drop the sid.
for sid in close_sids {
accum.pending_ops.push(PendingOp {
op: "close",
sid: Some(sid),
host: None,
port: None,
data: None,
encode_empty: false,
});
}
if accum.pending_ops.is_empty() {
continue;
}
fire_batch(&sems, &fronter, accum.pending_ops, accum.data_replies).await;
}
}
/// Per-iteration accumulator for `mux_loop`. Owns the three fields that
/// the data-bearing arms used to mutate in lockstep, with a single
/// `push_or_fire` entry point so the cap-then-push pattern lives in one
/// place instead of being copy-pasted into every arm.
struct BatchAccum {
pending_ops: Vec<PendingOp>,
data_replies: Vec<(usize, BatchedReply)>,
payload_bytes: usize,
}
impl BatchAccum {
fn new() -> Self {
Self {
pending_ops: Vec::new(),
data_replies: Vec::new(),
payload_bytes: 0,
}
}
/// Append `op` (with its `reply` channel and pre-computed `op_bytes`),
/// firing the current accumulator first if `op` would push us past
/// `MAX_BATCH_OPS` or `MAX_BATCH_PAYLOAD_BYTES`. After a fire the
/// accumulator is fresh for the new op.
async fn push_or_fire(
&mut self,
op: PendingOp,
op_bytes: usize,
reply: BatchedReply,
sems: &Arc<HashMap<String, Arc<Semaphore>>>,
fronter: &Arc<DomainFronter>,
) {
if should_fire(self.pending_ops.len(), self.payload_bytes, op_bytes) {
fire_batch(
sems,
fronter,
std::mem::take(&mut self.pending_ops),
std::mem::take(&mut self.data_replies),
)
.await;
self.payload_bytes = 0;
}
let idx = self.pending_ops.len();
self.pending_ops.push(op);
self.data_replies.push((idx, reply));
self.payload_bytes += op_bytes;
}
}
/// Threshold predicate for `BatchAccum::push_or_fire`: would adding an
/// op of `op_bytes` to a batch already holding `pending_len` ops and
/// `payload_bytes` of base64 cross either the per-batch op cap or
/// the payload-size cap?
///
/// Extracted from the inline `if` so the tunable boundary — including
/// the "first op never fires" rule (`pending_len == 0`) — has direct
/// unit-test coverage without spinning up a real `fire_batch`.
///
/// `saturating_add` keeps the helper's contract self-contained: a
/// pathological `op_bytes` near `usize::MAX` clamps to "yes, fire"
/// rather than wrapping around and silently letting an oversized op
/// slip past the cap. Today's callers only feed `encoded_len(n)` on
/// reasonable buffer sizes, but the predicate is the wrong place to
/// rely on caller bounds.
fn should_fire(pending_len: usize, payload_bytes: usize, op_bytes: usize) -> bool {
pending_len > 0
&& (pending_len >= MAX_BATCH_OPS
|| payload_bytes.saturating_add(op_bytes) > MAX_BATCH_PAYLOAD_BYTES)
}
/// Exact base64-encoded length of `n` raw bytes (standard padding):
/// `((n + 2) / 3) * 4`. Used by `mux_loop` to enforce
/// `MAX_BATCH_PAYLOAD_BYTES` without doing the actual encoding inline —
/// that work now happens in `fire_batch`'s spawned task.
fn encoded_len(n: usize) -> usize {
n.div_ceil(3) * 4
}
/// Build the wire-shape `BatchOp` from an internal `PendingOp`. Free
/// function so the encoding contract — non-empty data → encoded,
/// empty connect_data → `Some("")`, anything else empty → `None` — is
/// directly testable without spinning up the mux loop.
fn encode_pending(p: PendingOp) -> BatchOp {
let d = match (&p.data, p.encode_empty) {
(Some(b), _) if !b.is_empty() => Some(B64.encode(b)),
(Some(_), true) => Some(String::new()),
_ => None,
};
BatchOp {
op: p.op.into(),
sid: p.sid,
host: p.host,
port: p.port,
d,
}
}
/// Pick a deployment, acquire its per-account concurrency slot, and spawn
/// a batch request task.
///
/// The batch HTTP round-trip is bounded by `DomainFronter::batch_timeout()`
/// so a slow or dead tunnel-node target cannot hold a pipeline slot (and
/// block waiting sessions) forever. Each batch makes a single attempt —
/// no client-side retry against a different deployment, because
/// tunnel-node's `drain_now` mutates the per-session buffer when building
/// a response, so a lost response means lost bytes (silent gap on the
/// client side). Without server-side ack / sequence support a replay
/// would either duplicate writes (payload ops) or silently skip bytes
/// (empty polls). Sessions whose batch times out re-poll on the next
/// tick — same recovery surface as pre-#1088.
async fn fire_batch(
sems: &Arc<HashMap<String, Arc<Semaphore>>>,
fronter: &Arc<DomainFronter>,
pending_ops: Vec<PendingOp>,
data_replies: Vec<(usize, BatchedReply)>,
) {
let script_id = fronter.next_script_id();
let sem = sems
.get(&script_id)
.cloned()
.unwrap_or_else(|| Arc::new(Semaphore::new(CONCURRENCY_PER_DEPLOYMENT)));
let permit = sem.acquire_owned().await.unwrap();
let f = fronter.clone();
tokio::spawn(async move {
let _permit = permit;
let t0 = std::time::Instant::now();
let n_ops = pending_ops.len();
// Encode payloads to base64 here, off the single mux thread.
// With 50 ops × 64 KB this is up to ~3 MB of work; doing it on
// the mux task previously serialized every op behind whichever
// batch was currently encoding.
let data_ops: Vec<BatchOp> = pending_ops.into_iter().map(encode_pending).collect();
// Bounded-wait: if the batch takes longer than the configured
// batch timeout (Config::request_timeout_secs), all sessions in
// this batch get an error and can retry-poll on the next tick.
let batch_timeout = f.batch_timeout();
let result = tokio::time::timeout(
batch_timeout,
f.tunnel_batch_request_to(&script_id, &data_ops),
)
.await;
let sid_short = &script_id[..script_id.len().min(8)];
let rtt = t0.elapsed();
f.h2_open_timeout.store((rtt.as_secs() * 4 + 1).clamp(8, 20), Ordering::SeqCst);
tracing::info!(
"batch: {} ops → {}, rtt={:?}",
n_ops,
sid_short,
rtt
);
match result {
Ok(Ok(batch_resp)) => {
f.record_batch_success(&script_id);
// Wire the Full-mode usage counter that #230 / #362 flagged
// as stuck-at-zero. Each successful batch is one
// `UrlFetchApp.fetch()` call against the deploying Google
// account's daily quota — bytes-counted is the inbound JSON
// response which is the closest analogue to the apps_script
// path's `record_today(bytes_received)` (we don't have the
// exact response byte count post-deserialize, so we use a
// proxy: sum of per-session response payload bytes the
// batch carried back). Underestimates by JSON envelope
// overhead but is in the right order of magnitude.
let response_bytes: u64 = batch_resp
.r
.iter()
.map(|r| {
// `d` carries TCP payload (base64 string len ≈
// 4/3 of decoded bytes; close enough); `pkts`
// carries UDP datagrams (each base64); plus any
// error string. Sum gives a stable proxy for
// "how much did this batch move."
let d = r.d.as_ref().map(|s| s.len() as u64).unwrap_or(0);
let pkts = r
.pkts
.as_ref()
.map(|v| v.iter().map(|p| p.len() as u64).sum::<u64>())
.unwrap_or(0);
d + pkts
})
.sum();
f.record_today(response_bytes);
for (idx, reply) in data_replies {
if let Some(resp) = batch_resp.r.get(idx) {
let _ = reply.send(Ok((resp.clone(), script_id.clone())));
} else {
let _ = reply.send(Err(format!(
"missing response in batch from script {}",
sid_short
)));
}
}
}
Ok(Err(e)) => {
// Read-side timeout from `domain_fronter`: Apps Script didn't
// start streaming response bytes within the per-read deadline.
// Common cause: deployment's `TUNNEL_SERVER_URL` points at a
// dead host, so UrlFetchApp inside Apps Script hangs until its
// own internal connect timeout. Strike-counter blacklists the
// deployment after a sustained pattern.
if matches!(e, FronterError::Timeout) {
f.record_timeout_strike(&script_id);
}
let err_msg = format!("{}", e);
// Decoy / Apps-Script-flake detection. This body string can
// mean any of 4 unrelated things (AUTH_KEY mismatch, Apps
// Script execution timeout, Google-side flake, ISP-side
// truncation #313), so surface all candidates rather than
// asserting one. Operators can flip DIAGNOSTIC_MODE in
// Code.gs to disambiguate (#404).
if err_msg.contains("The script completed but did not return anything") {
tracing::error!(
"batch failed (script {}): got the v1.8.0 decoy/placeholder body — \
could be (1) AUTH_KEY mismatch between mhrv-rs config and Code.gs \
(run a direct curl probe against the deployment to verify), \
(2) Apps Script execution timeout or per-100s quota tear (try \
lowering parallel_concurrency in config), (3) Apps Script \
internal hiccup (transient, retry next batch), or (4) ISP-side \
response truncation (#313 pattern, try a different google_ip). \