Skip to content

Commit fb45ba1

Browse files
fix(compression): backward-compatible zstd with automatic fallback
- Send zops (compressed) by default, fall back to ops on mismatch - zc flag signals response compression support to tunnel-node - Old tunnel-node/Apps Script: returns empty r[], client detects mismatch and disables zops for subsequent batches - Response compression (zr) still works even after request fallback - Apps Script passes zc through to tunnel-node for response path Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent f7e1b32 commit fb45ba1

4 files changed

Lines changed: 42 additions & 36 deletions

File tree

‎assets/apps_script/CodeFull.gs‎

Lines changed: 12 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -201,16 +201,12 @@ function _doTunnel(req) {
201201
// On a 5-DNS-query batch, this collapses 5 serial cache.get round trips
202202
// into one cache.getAll round trip.
203203
function _doTunnelBatch(req) {
204-
// Compressed batch: forward opaquely, skip edge-DNS inspection.
205-
if (req.zops) {
206-
return _doTunnelBatchForwardCompressed(req.zops);
207-
}
208-
209204
var ops = (req && req.ops) || [];
205+
var zc = req && req.zc;
210206

211207
// Feature off: byte-identical to the pre-feature behavior.
212208
if (!ENABLE_EDGE_DNS_CACHE) {
213-
return _doTunnelBatchForward(ops);
209+
return _doTunnelBatchForward(ops, zc);
214210
}
215211

216212
var results = new Array(ops.length); // sparse: filled by edge-DNS hits
@@ -277,10 +273,11 @@ function _doTunnelBatch(req) {
277273

278274
// Nothing was served locally — forward verbatim, no splice needed.
279275
if (forwardOps.length === ops.length) {
280-
return _doTunnelBatchForward(ops);
276+
return _doTunnelBatchForward(ops, zc);
281277
}
282278

283279
// Partial: forward the un-served ops and splice results back in place.
280+
// Don't pass zc here — Apps Script needs to parse r[] for splicing.
284281
var resp = _doTunnelBatchFetch(forwardOps);
285282
if (resp.error) return _json({ e: resp.error });
286283
if (resp.r.length !== forwardOps.length) {
@@ -292,28 +289,13 @@ function _doTunnelBatch(req) {
292289
}
293290

294291
// Verbatim forward: no splice, response passed through unchanged.
295-
function _doTunnelBatchForward(ops) {
296-
var resp = UrlFetchApp.fetch(TUNNEL_SERVER_URL + "/tunnel/batch", {
297-
method: "post",
298-
contentType: "application/json",
299-
payload: JSON.stringify({ k: TUNNEL_AUTH_KEY, ops: ops }),
300-
muteHttpExceptions: true,
301-
followRedirects: true,
302-
});
303-
if (resp.getResponseCode() !== 200) {
304-
return _json({ e: "tunnel batch HTTP " + resp.getResponseCode() });
305-
}
306-
return ContentService.createTextOutput(resp.getContentText())
307-
.setMimeType(ContentService.MimeType.JSON);
308-
}
309-
310-
// Compressed forward: zops is an opaque blob, passed to tunnel-node as-is.
311-
// Response is also opaque (may contain zr instead of r).
312-
function _doTunnelBatchForwardCompressed(zops) {
292+
function _doTunnelBatchForward(ops, zc) {
293+
var body = { k: TUNNEL_AUTH_KEY, ops: ops };
294+
if (zc) body.zc = zc;
313295
var resp = UrlFetchApp.fetch(TUNNEL_SERVER_URL + "/tunnel/batch", {
314296
method: "post",
315297
contentType: "application/json",
316-
payload: JSON.stringify({ k: TUNNEL_AUTH_KEY, zops: zops }),
298+
payload: JSON.stringify(body),
317299
muteHttpExceptions: true,
318300
followRedirects: true,
319301
});
@@ -326,11 +308,13 @@ function _doTunnelBatchForwardCompressed(zops) {
326308

327309
// Forward + parse for the splice path. Returns { r:[...] } on success or
328310
// { error: "..." } on any failure.
329-
function _doTunnelBatchFetch(ops) {
311+
function _doTunnelBatchFetch(ops, zc) {
312+
var body = { k: TUNNEL_AUTH_KEY, ops: ops };
313+
if (zc) body.zc = zc;
330314
var resp = UrlFetchApp.fetch(TUNNEL_SERVER_URL + "/tunnel/batch", {
331315
method: "post",
332316
contentType: "application/json",
333-
payload: JSON.stringify({ k: TUNNEL_AUTH_KEY, ops: ops }),
317+
payload: JSON.stringify(body),
334318
muteHttpExceptions: true,
335319
followRedirects: true,
336320
});

‎src/domain_fronter.rs‎

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -412,6 +412,7 @@ pub struct DomainFronter {
412412
/// payloads. Mirrors `Config::disable_padding` (#391). Default false
413413
/// (padding active = stronger DPI defense at +25% bandwidth cost).
414414
disable_padding: bool,
415+
zstd_unsupported: Arc<AtomicBool>,
415416
/// Per-instance auto-blacklist tuning. Mirrors `Config::auto_blacklist_*`
416417
/// (#391, #444). Cached here so the hot path in `record_timeout_strike`
417418
/// doesn't have to reach back through the Config (which we don't keep
@@ -628,6 +629,7 @@ impl DomainFronter {
628629
today_bytes: AtomicU64::new(0),
629630
today_key: std::sync::Mutex::new(current_pt_day_key()),
630631
disable_padding: config.disable_padding,
632+
zstd_unsupported: Arc::new(AtomicBool::new(false)),
631633
auto_blacklist_strikes: config.auto_blacklist_strikes.max(1),
632634
auto_blacklist_window: Duration::from_secs(
633635
config.auto_blacklist_window_secs.clamp(1, 3600),
@@ -693,6 +695,13 @@ impl DomainFronter {
693695
self.batch_timeout
694696
}
695697

698+
pub(crate) fn mark_zstd_unsupported(&self) {
699+
if !self.zstd_unsupported.load(Ordering::Relaxed) {
700+
tracing::warn!("zstd batch compression not supported by deployment, falling back to uncompressed");
701+
self.zstd_unsupported.store(true, Ordering::Relaxed);
702+
}
703+
}
704+
696705
/// Record one relay call toward the daily budget. Called once per
697706
/// outbound Apps Script fetch. Rolls over both daily counters at
698707
/// 00:00 Pacific Time, matching Apps Script's quota reset cadence
@@ -3107,14 +3116,22 @@ impl DomainFronter {
31073116
let mut map = serde_json::Map::new();
31083117
map.insert("k".into(), Value::String(self.auth_key.clone()));
31093118
map.insert("t".into(), Value::String("batch".into()));
3110-
let ops_json = serde_json::to_vec(ops)?;
3111-
match zstd::encode_all(ops_json.as_slice(), 3) {
3112-
Ok(compressed) => {
3113-
map.insert("zops".into(), Value::String(B64.encode(&compressed)));
3114-
}
3115-
Err(_) => {
3116-
map.insert("ops".into(), serde_json::to_value(ops)?);
3119+
let use_zstd = !self.zstd_unsupported.load(Ordering::Relaxed);
3120+
if use_zstd {
3121+
let ops_json = serde_json::to_vec(ops)?;
3122+
match zstd::encode_all(ops_json.as_slice(), 3) {
3123+
Ok(compressed) => {
3124+
map.insert("zops".into(), Value::String(B64.encode(&compressed)));
3125+
map.insert("zc".into(), Value::Number(1.into()));
3126+
}
3127+
Err(_) => {
3128+
map.insert("ops".into(), serde_json::to_value(ops)?);
3129+
map.insert("zc".into(), Value::Number(1.into()));
3130+
}
31173131
}
3132+
} else {
3133+
map.insert("ops".into(), serde_json::to_value(ops)?);
3134+
map.insert("zc".into(), Value::Number(1.into()));
31183135
}
31193136
if !self.disable_padding {
31203137
add_random_pad(&mut map);

‎src/tunnel_client.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1105,6 +1105,9 @@ async fn fire_batch(
11051105
"batch response mismatch: idx={} but r.len()={} (sent {} ops) from script {}",
11061106
idx, batch_resp.r.len(), n_ops, sid_short,
11071107
);
1108+
if batch_resp.r.is_empty() && n_ops > 0 {
1109+
f.mark_zstd_unsupported();
1110+
}
11081111
let _ = reply.send(Err(format!(
11091112
"missing response in batch from script {}",
11101113
sid_short

‎tunnel-node/src/main.rs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -680,6 +680,8 @@ struct BatchRequest {
680680
ops: Vec<BatchOp>,
681681
#[serde(default)]
682682
zops: Option<String>,
683+
#[serde(default)]
684+
zc: Option<u8>,
683685
}
684686

685687
#[derive(Deserialize)]
@@ -775,7 +777,7 @@ async fn handle_batch(
775777
}
776778
};
777779

778-
let client_zstd = req.zops.is_some();
780+
let client_zstd = req.zops.is_some() || req.zc.is_some();
779781
let ops: Vec<BatchOp> = if let Some(zops_b64) = req.zops {
780782
match B64.decode(&zops_b64) {
781783
Ok(compressed) => match zstd::decode_all(compressed.as_slice()) {

0 commit comments

Comments
 (0)