@@ -55,28 +55,20 @@ const REPLY_TIMEOUT: Duration = Duration::from_secs(35);
5555/// connect saves one Apps Script round-trip per new flow.
5656const CLIENT_FIRST_DATA_WAIT : Duration = Duration :: from_millis ( 50 ) ;
5757
58- /// How long the muxer holds open the batch buffer after the first op
59- /// arrives, waiting for more ops to coalesce. Issue #231 — the previous
60- /// implementation drained `try_recv()` *immediately* after the first
61- /// message landed, so under any non-bursty workload every batch held
62- /// exactly one op (defeating the entire batching premise). 8 ms is small
63- /// vs the ~2-7 s Apps Script round-trip the batch is amortizing, but
64- /// long enough that concurrent HTTP/2 stream openings, parallel fetches,
65- /// or any other burst lands in the same batch.
66- const BATCH_COALESCE_WINDOW : Duration = Duration :: from_millis ( 8 ) ;
58+ /// Adaptive coalesce defaults: after each new op arrives, wait another
59+ /// step for more ops. Resets on every arrival, up to max from the first
60+ /// op. Overridable via config `coalesce_step_ms` / `coalesce_max_ms`.
61+ const DEFAULT_COALESCE_STEP_MS : u64 = 40 ;
62+ const DEFAULT_COALESCE_MAX_MS : u64 = 1000 ;
6763
6864/// Structured error code the tunnel-node returns when it doesn't know the
6965/// op (version mismatch). Must match `tunnel-node/src/main.rs`.
7066const CODE_UNSUPPORTED_OP : & str = "UNSUPPORTED_OP" ;
7167
72- /// Empty poll round-trip latency below which we conclude the tunnel-node
73- /// is *not* long-polling (legacy fixed-sleep drain instead). On a
74- /// long-poll-capable server an empty poll with no upstream push either
75- /// returns near `LONGPOLL_DEADLINE` (~5 s) or comes back early *with*
76- /// pushed bytes — neither matches a fast empty reply. Threshold sits
77- /// well above the legacy `~350 ms` drain and well below the long-poll
78- /// floor, so network jitter on either side won't false-trigger.
79- const LEGACY_DETECT_THRESHOLD : Duration = Duration :: from_millis ( 1500 ) ;
68+ /// Legacy tunnel-node detection threshold. Set to 0 to disable — users
69+ /// who deploy their own tunnel-node don't need auto-detection, and the
70+ /// heuristic triggered false positives with longer drain/settle times.
71+ const LEGACY_DETECT_THRESHOLD : Duration = Duration :: from_millis ( 0 ) ;
8072
8173/// How long a deployment stays in "legacy / no long-poll" mode after the
8274/// last detection. Must be much longer than `LEGACY_DETECT_THRESHOLD` so a
@@ -255,7 +247,7 @@ pub struct TunnelMux {
255247}
256248
257249impl TunnelMux {
258- pub fn start ( fronter : Arc < DomainFronter > ) -> Arc < Self > {
250+ pub fn start ( fronter : Arc < DomainFronter > , coalesce_step_ms : u64 , coalesce_max_ms : u64 ) -> Arc < Self > {
259251 // Dedupe before snapshotting: the aggregate `all_legacy` gate
260252 // compares `legacy_deployments.len()` (a HashMap, so unique
261253 // keys) against this count, so using the raw `num_scripts()`
@@ -280,8 +272,11 @@ impl TunnelMux {
280272 unique_n,
281273 CONCURRENCY_PER_DEPLOYMENT
282274 ) ;
275+ let step = if coalesce_step_ms > 0 { coalesce_step_ms } else { DEFAULT_COALESCE_STEP_MS } ;
276+ let max = if coalesce_max_ms > 0 { coalesce_max_ms } else { DEFAULT_COALESCE_MAX_MS } ;
277+ tracing:: info!( "batch coalesce: step={}ms max={}ms" , step, max) ;
283278 let ( tx, rx) = mpsc:: channel ( 512 ) ;
284- tokio:: spawn ( mux_loop ( rx, fronter) ) ;
279+ tokio:: spawn ( mux_loop ( rx, fronter, step , max ) ) ;
285280 Arc :: new ( Self {
286281 tx,
287282 connect_data_unsupported : Arc :: new ( AtomicBool :: new ( false ) ) ,
@@ -556,7 +551,9 @@ impl TunnelMux {
556551 }
557552}
558553
559- async fn mux_loop ( mut rx : mpsc:: Receiver < MuxMsg > , fronter : Arc < DomainFronter > ) {
554+ async fn mux_loop ( mut rx : mpsc:: Receiver < MuxMsg > , fronter : Arc < DomainFronter > , coalesce_step_ms : u64 , coalesce_max_ms : u64 ) {
555+ let coalesce_step = Duration :: from_millis ( coalesce_step_ms) ;
556+ let coalesce_max = Duration :: from_millis ( coalesce_max_ms) ;
560557 // One semaphore per deployment ID, each allowing 30 concurrent requests.
561558 let sems: Arc < HashMap < String , Arc < Semaphore > > > = Arc :: new (
562559 fronter
@@ -581,20 +578,28 @@ async fn mux_loop(mut rx: mpsc::Receiver<MuxMsg>, fronter: Arc<DomainFronter>) {
581578 Some ( msg) => msgs. push ( msg) ,
582579 None => break ,
583580 }
584- let deadline = tokio:: time:: Instant :: now ( ) + BATCH_COALESCE_WINDOW ;
581+ let hard_deadline = tokio:: time:: Instant :: now ( ) + coalesce_max;
582+ let mut soft_deadline = tokio:: time:: Instant :: now ( ) + coalesce_step;
585583 loop {
586584 // Drain anything that's already queued without waiting.
587585 while let Ok ( msg) = rx. try_recv ( ) {
588586 msgs. push ( msg) ;
587+ // Reset the soft deadline — more ops are arriving.
588+ soft_deadline = tokio:: time:: Instant :: now ( ) + coalesce_step;
589589 }
590590 let now = tokio:: time:: Instant :: now ( ) ;
591- if now >= deadline {
591+ let wait_until = soft_deadline. min ( hard_deadline) ;
592+ if now >= wait_until {
592593 break ;
593594 }
594- match tokio:: time:: timeout ( deadline - now, rx. recv ( ) ) . await {
595- Ok ( Some ( msg) ) => msgs. push ( msg) ,
595+ match tokio:: time:: timeout ( wait_until - now, rx. recv ( ) ) . await {
596+ Ok ( Some ( msg) ) => {
597+ msgs. push ( msg) ;
598+ // New op arrived — extend the soft deadline.
599+ soft_deadline = tokio:: time:: Instant :: now ( ) + coalesce_step;
600+ }
596601 Ok ( None ) => return ,
597- Err ( _) => break ,
602+ Err ( _) => break , // soft or hard deadline hit, no more ops
598603 }
599604 }
600605
@@ -787,11 +792,9 @@ async fn mux_loop(mut rx: mpsc::Receiver<MuxMsg>, fronter: Arc<DomainFronter>) {
787792}
788793
789794/// Pick a deployment, acquire its per-account concurrency slot, and spawn
790- /// a batch request task.
791- ///
792- /// The batch HTTP round-trip is bounded by `BATCH_TIMEOUT` so a slow or
793- /// dead tunnel-node target cannot hold a pipeline slot (and block waiting
794- /// sessions) forever.
795+ /// a batch request task. The semaphore acquire blocks the mux_loop until
796+ /// a slot opens — this is intentional: under heavy load, ops pile up in
797+ /// the channel and get collected into bigger batches on the next iteration.
795798async fn fire_batch (
796799 sems : & Arc < HashMap < String , Arc < Semaphore > > > ,
797800 fronter : & Arc < DomainFronter > ,
0 commit comments