Skip to content

Commit d85f3aa

Browse files
vahidlazioclaude
andcommitted
feat: per-deployment concurrency (30 req/account) instead of global pipeline depth
Apps Script enforces 30 concurrent executions per account. The old pipeline used a single global semaphore sized to the number of deployments, meaning 1 in-flight batch per deployment. Now each deployment ID gets its own semaphore with 30 permits — matching the actual per-account limit. With N deployments the system can sustain 30×N concurrent batch requests instead of N. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent c407e98 commit d85f3aa

3 files changed

Lines changed: 76 additions & 46 deletions

File tree

README.md

Lines changed: 24 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,7 @@ Firefox keeps its own cert store; the installer also drops the CA into Firefox's
163163

164164
Open the UI and fill in the form:
165165

166-
- **Apps Script ID** — the Deployment ID from Step 1. Add multiple IDs (one per line in the UI, or a JSON array in `config.json`) for higher quota **and** lower latency. In `apps_script` mode, IDs are round-robined. In `full` mode, more IDs directly increase the pipeline depth (see [Full tunnel mode](#full-tunnel-mode) below).
166+
- **Apps Script ID** — the Deployment ID from Step 1. Add multiple IDs (one per line in the UI, or a JSON array in `config.json`) for higher quota **and** lower latency. In `apps_script` mode, IDs are round-robined. In `full` mode, each deployment gets its own pool of 30 concurrent requests (the Apps Script per-account limit), so more IDs = more total throughput (see [Full tunnel mode](#full-tunnel-mode) below).
167167
- **Auth key** — the same secret you set in `Code.gs`.
168168
- **Google IP**`216.239.38.120` is a solid default. Use the **scan** button to probe for a faster one from your network.
169169
- **Front domain** — keep `www.google.com`.
@@ -271,21 +271,20 @@ Full tunnel mode (`"mode": "full"`) routes **all** traffic end-to-end through Ap
271271

272272
### How deployment IDs affect performance
273273

274-
Each Apps Script batch request takes ~2 seconds round-trip. In full mode, `mhrv-rs` runs a **pipelined batch multiplexer** that fires multiple batch requests concurrently without waiting for the previous one to return. The number of in-flight batches (the *pipeline depth*) scales directly with the number of deployment IDs you configure:
274+
Each Apps Script batch request takes ~2 seconds round-trip. In full mode, `mhrv-rs` runs a **pipelined batch multiplexer** that fires multiple batch requests concurrently without waiting for the previous one to return. Each deployment ID (= one Google account) gets its own concurrency pool of **30 in-flight requests** — matching the Apps Script per-account execution limit.
275275

276276
```
277-
pipeline_depth = number_of_script_ids (minimum 2)
277+
max_concurrent = 30 × number_of_deployment_ids
278278
```
279279

280-
| Deployments | Pipeline depth | Effective batch interval | Notes |
281-
|-------------|---------------|------------------------|-------|
282-
| 1 | 2 | ~1.0s | Minimum — still pipelines 2 batches |
283-
| 3 | 3 | ~0.7s | Good for light browsing |
284-
| 6 | 6 | ~0.3s | Recommended for daily use |
285-
| 12 | 12 | ~0.17s | Sweet spot for most users |
286-
| 20 | 20 | ~0.10s | Multi-account setups |
280+
| Deployments | Concurrent requests | Notes |
281+
|-------------|-------------------|-------|
282+
| 1 | 30 | Single account — plenty for light browsing |
283+
| 3 | 90 | Good for daily use |
284+
| 6 | 180 | Recommended for heavy use |
285+
| 12 | 360 | Multi-account power setup |
287286

288-
More deployments = more concurrent batches = lower per-session latency. Each batch round-robins across your deployment IDs, so the load is spread evenly and you're less likely to hit a single deployment's quota ceiling.
287+
More deployments = more total concurrency = lower per-session latency. Each batch round-robins across your deployment IDs, so the load is spread evenly and you're less likely to hit a single deployment's quota ceiling.
289288

290289
**Resource guards** keep things safe:
291290
- **50 ops max** per batch — if more sessions are active, the mux splits into multiple batches
@@ -294,10 +293,10 @@ More deployments = more concurrent batches = lower per-session latency. Each bat
294293

295294
### Quick start
296295

297-
1. Deploy [`CodeFull.gs`](assets/apps_script/CodeFull.gs) as **3–12 Web App deployments** (same steps as `Code.gs`, but use the full-mode script that forwards to your tunnel-node). You can create multiple deployments on a single Google account — each "New deployment" produces its own ID. Going multi-account only matters for the daily quota (each Google account gets its own 20 000 `UrlFetchApp` calls/day on the free tier / 100 000 on Workspace); the pipeline depth itself scales fine on one account up to Apps Script's simultaneous-execution ceiling. Rule of thumb:
298-
- **Solo use**3–6 deployments on one account is plenty
299-
- **Shared with ~3 people**6 deployments on one account, bump to multi-account only if you start hitting quota alerts
300-
- **Shared with a group** → one account per heavy user (each with 1–2 deployments) is the clean scaling path
296+
1. Deploy [`CodeFull.gs`](assets/apps_script/CodeFull.gs) as a **Web App deployment** on each Google account (same steps as `Code.gs`, but use the full-mode script that forwards to your tunnel-node). Use **one deployment per Google account**the 30-concurrent-request limit is per account, so multiple deployments on the same account share the same pool and don't add concurrency. To scale, add more accounts:
297+
- **Solo use**1–2 accounts is plenty
298+
- **Shared with ~3 people**3 accounts
299+
- **Shared with a group** → one account per heavy user
301300
2. Deploy the [tunnel-node](tunnel-node/) on a VPS
302301
3. Set `"mode": "full"` in your config with all deployment IDs:
303302

@@ -630,21 +629,20 @@ Donations cover hosting, self-hosted CI runner costs, and continued maintenance.
630629

631630
#### چرا تعداد `Deployment ID` مهم است؟
632631

633-
هر درخواست دسته‌ای (`batch`) به `Apps Script` حدود ۲ ثانیه طول می‌کشد. در حالت `full`، برنامه یک **لولهٔ موازی** (`pipeline`) اجرا می‌کند که چند درخواست دسته‌ای را همزمان می‌فرستد بدون اینکه منتظر پاسخ قبلی بماند. تعداد درخواست‌های همزمان مستقیماً با تعداد `Deployment ID`ها رابطه دارد:
632+
هر درخواست دسته‌ای (`batch`) به `Apps Script` حدود ۲ ثانیه طول می‌کشد. در حالت `full`، برنامه یک **لولهٔ موازی** (`pipeline`) اجرا می‌کند که چند درخواست دسته‌ای را همزمان می‌فرستد بدون اینکه منتظر پاسخ قبلی بماند. هر `Deployment ID` (= یک حساب گوگل) حوضچهٔ همزمانی مخصوص خودش با **۳۰ درخواست همزمان** دارد — مطابق سقف اجرای همزمان `Apps Script` به ازای هر حساب.
634633

635634
```
636-
عمق لوله = تعداد Deployment IDها (حداقل ۲)
635+
حداکثر همزمانی = ۳۰ × تعداد Deployment IDها
637636
```
638637

639-
| تعداد Deployment | عمق لوله | فاصلهٔ مؤثر بین دسته‌ها | |
640-
|-----------------|----------|------------------------|---|
641-
| ۱ | ۲ | ~۱ ثانیه | حداقل |
642-
| ۳ | ۳ | ~۰.۷ ثانیه | مناسب مرور سبک |
643-
| ۶ | ۶ | ~۰.۳ ثانیه | توصیه‌شده برای استفادهٔ روزانه |
644-
| ۱۲ | ۱۲ | ~۰.۱۷ ثانیه | نقطهٔ بهینه |
645-
| ۲۰ | ۲۰ | ~۰.۱ ثانیه | چند حساب |
638+
| تعداد Deployment | درخواست‌های همزمان | |
639+
|-----------------|-------------------|---|
640+
| ۱ | ۳۰ | یک حساب — برای مرور سبک کافیست |
641+
| ۳ | ۹۰ | مناسب استفادهٔ روزانه |
642+
| ۶ | ۱۸۰ | توصیه‌شده برای استفادهٔ سنگین |
643+
| ۱۲ | ۳۶۰ | چند حساب — حداکثر توان |
646644

647-
بیشتر `Deployment` = بیشتر درخواست همزمان = تأخیر کمتر برای هر نشست. هر دسته بین `ID`ها چرخش می‌کند (`round-robin`)، پس بار به‌طور یکنواخت توزیع می‌شود.
645+
بیشتر `Deployment` = بیشتر همزمانی = تأخیر کمتر برای هر نشست. هر دسته بین `ID`ها چرخش می‌کند (`round-robin`)، پس بار به‌طور یکنواخت توزیع می‌شود.
648646

649647
### اجرا روی OpenWRT (روتر)
650648

@@ -700,7 +698,7 @@ logread -e mhrv-rs -f
700698
- **لینوکس:** فایل `/usr/local/share/ca-certificates/mhrv-rs.crt` را حذف و `sudo update-ca-certificates` اجرا کنید
701699

702700
**چند `Deployment ID` لازم دارم؟**
703-
یکی برای استفادهٔ عادی کافی است. سهمیهٔ روزانه `UrlFetchApp` برای حساب رایگان گوگل **۲۰٬۰۰۰ درخواست در روز** است (برای `Workspace` پولی ۱۰۰٬۰۰۰)، با محدودیت پاسخ ۵۰ مگابایت به ازای هر `fetch`. برای اکثر کاربران چند ساعت یوتیوب هم با یک `Deployment` کافی است. می‌توانید چند `Deployment` **در همان حساب** بسازید (هر بار `New deployment` یک `ID` جدید می‌دهد) — این روش در حالت `full` پهنای باند بهتری می‌دهد چون `pipeline depth` افزایش پیدا می‌کند و هر `Deployment` یک اجرای همزمان جدا در `Apps Script` می‌گیرد (تا سقف ۳۰ اجرای همزمان هر حساب). برای سهمیهٔ روزانهٔ بیشتر، در حساب‌های گوگل دیگر هم `Deployment` بسازید — هر حساب سهمیهٔ ۲۰ هزار درخواستی خودش را دارد. همهٔ `ID`ها را در فیلد `Apps Script ID(s)` وارد کنید — برنامه خودکار بینشان می‌چرخد. مرجع: <https://developers.google.com/apps-script/guides/services/quotas>
701+
یکی برای استفادهٔ عادی کافی است. سهمیهٔ روزانه `UrlFetchApp` برای حساب رایگان گوگل **۲۰٬۰۰۰ درخواست در روز** است (برای `Workspace` پولی ۱۰۰٬۰۰۰)، با محدودیت پاسخ ۵۰ مگابایت به ازای هر `fetch`. از هر حساب گوگل **فقط یک `Deployment`** بسازید — سقف ۳۰ درخواست همزمان به ازای هر حساب است، پس چند `Deployment` روی یک حساب همزمانی اضافه نمی‌کند. برای افزایش همزمانی یا سهمیهٔ روزانه، در حساب‌های گوگل دیگر `Deployment` بسازید — هر حساب سهمیهٔ ۲۰ هزار درخواستی و ۳۰ اجرای همزمان خودش را دارد. همهٔ `ID`ها را در فیلد `Apps Script ID(s)` وارد کنید — برنامه خودکار بینشان می‌چرخد. مرجع: <https://developers.google.com/apps-script/guides/services/quotas>
704702

705703
**یوتوب کار می‌کند؟ ویدیو پخش می‌شود؟**
706704
صفحهٔ یوتوب سریع باز می‌شود (چون مستقیم از لبهٔ گوگل می‌آید). اما `chunk`های ویدیوی اصلی از `googlevideo.com` از طریق `Apps Script` می‌آیند و روزانه سهمیه دارند. برای تماشای گاه‌به‌گاه خوب است، برای ۱۰۸۰p پخش طولانی دردناک.

src/domain_fronter.rs

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -336,6 +336,10 @@ impl DomainFronter {
336336
self.script_ids.len()
337337
}
338338

339+
pub fn script_id_list(&self) -> &[String] {
340+
&self.script_ids
341+
}
342+
339343
pub fn cache(&self) -> &ResponseCache {
340344
&self.cache
341345
}
@@ -344,7 +348,7 @@ impl DomainFronter {
344348
self.coalesced.load(Ordering::Relaxed)
345349
}
346350

347-
fn next_script_id(&self) -> String {
351+
pub fn next_script_id(&self) -> String {
348352
let n = self.script_ids.len();
349353
let mut bl = self.blacklist.lock().unwrap();
350354
let now = Instant::now();
@@ -1169,14 +1173,25 @@ impl DomainFronter {
11691173
pub async fn tunnel_batch_request(
11701174
&self,
11711175
ops: &[BatchOp],
1176+
) -> Result<BatchTunnelResponse, FronterError> {
1177+
let script_id = self.next_script_id();
1178+
self.tunnel_batch_request_to(&script_id, ops).await
1179+
}
1180+
1181+
/// Like `tunnel_batch_request` but targets a specific deployment ID.
1182+
/// Used by the pipeline mux to pin a batch to a deployment whose
1183+
/// per-account concurrency slot has already been acquired.
1184+
pub async fn tunnel_batch_request_to(
1185+
&self,
1186+
script_id: &str,
1187+
ops: &[BatchOp],
11721188
) -> Result<BatchTunnelResponse, FronterError> {
11731189
let mut map = serde_json::Map::new();
11741190
map.insert("k".into(), Value::String(self.auth_key.clone()));
11751191
map.insert("t".into(), Value::String("batch".into()));
11761192
map.insert("ops".into(), serde_json::to_value(ops)?);
11771193
let payload = serde_json::to_vec(&Value::Object(map))?;
11781194

1179-
let script_id = self.next_script_id();
11801195
let path = format!("/macros/s/{}/exec", script_id);
11811196

11821197
let mut entry = self.acquire().await?;

src/tunnel_client.rs

Lines changed: 35 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,10 @@
22
//!
33
//! A central multiplexer collects pending data from ALL active sessions
44
//! and fires batch requests without waiting for the previous one to return.
5-
//! Pipeline depth equals the number of script deployments (minimum 2),
6-
//! so users with more deployments get lower latency automatically.
5+
//! Each Apps Script deployment (account) gets its own concurrency pool of
6+
//! 30 in-flight requests — matching the per-account Apps Script limit.
77
8+
use std::collections::HashMap;
89
use std::sync::Arc;
910
use std::time::Duration;
1011

@@ -16,8 +17,8 @@ use tokio::sync::{mpsc, oneshot, Semaphore};
1617

1718
use crate::domain_fronter::{BatchOp, DomainFronter, TunnelResponse};
1819

19-
/// Minimum pipeline depth even with a single script.
20-
const MIN_PIPELINE_DEPTH: usize = 2;
20+
/// Apps Script allows 30 concurrent executions per account / deployment.
21+
const CONCURRENCY_PER_DEPLOYMENT: usize = 30;
2122

2223
/// Maximum total base64-encoded payload bytes in a single batch request.
2324
/// Apps Script accepts up to 50 MB per fetch, but the tunnel-node must
@@ -66,14 +67,14 @@ pub struct TunnelMux {
6667

6768
impl TunnelMux {
6869
pub fn start(fronter: Arc<DomainFronter>) -> Arc<Self> {
69-
let pipeline_depth = fronter.num_scripts().max(MIN_PIPELINE_DEPTH);
70+
let n = fronter.num_scripts();
7071
tracing::info!(
71-
"tunnel mux: pipeline_depth={} (from {} script deployments)",
72-
pipeline_depth,
73-
fronter.num_scripts()
72+
"tunnel mux: {} deployment(s), {} concurrent per deployment",
73+
n,
74+
CONCURRENCY_PER_DEPLOYMENT
7475
);
7576
let (tx, rx) = mpsc::channel(512);
76-
tokio::spawn(mux_loop(rx, fronter, pipeline_depth));
77+
tokio::spawn(mux_loop(rx, fronter));
7778
Arc::new(Self { tx })
7879
}
7980

@@ -85,9 +86,15 @@ impl TunnelMux {
8586
async fn mux_loop(
8687
mut rx: mpsc::Receiver<MuxMsg>,
8788
fronter: Arc<DomainFronter>,
88-
pipeline_depth: usize,
8989
) {
90-
let sem = Arc::new(Semaphore::new(pipeline_depth));
90+
// One semaphore per deployment ID, each allowing 30 concurrent requests.
91+
let sems: Arc<HashMap<String, Arc<Semaphore>>> = Arc::new(
92+
fronter
93+
.script_id_list()
94+
.iter()
95+
.map(|id| (id.clone(), Arc::new(Semaphore::new(CONCURRENCY_PER_DEPLOYMENT))))
96+
.collect(),
97+
);
9198

9299
loop {
93100
let mut msgs = Vec::new();
@@ -136,7 +143,7 @@ async fn mux_loop(
136143
|| batch_payload_bytes + op_bytes > MAX_BATCH_PAYLOAD_BYTES)
137144
{
138145
fire_batch(
139-
&sem,
146+
&sems,
140147
&fronter,
141148
std::mem::take(&mut data_ops),
142149
std::mem::take(&mut data_replies),
@@ -176,22 +183,28 @@ async fn mux_loop(
176183
continue;
177184
}
178185

179-
fire_batch(&sem, &fronter, data_ops, data_replies).await;
186+
fire_batch(&sems, &fronter, data_ops, data_replies).await;
180187
}
181188
}
182189

183-
/// Acquire a pipeline slot and spawn a batch request task.
190+
/// Pick a deployment, acquire its per-account concurrency slot, and spawn
191+
/// a batch request task.
184192
///
185193
/// The batch HTTP round-trip is bounded by `BATCH_TIMEOUT` so a slow or
186194
/// dead tunnel-node target cannot hold a pipeline slot (and block waiting
187195
/// sessions) forever.
188196
async fn fire_batch(
189-
sem: &Arc<Semaphore>,
197+
sems: &Arc<HashMap<String, Arc<Semaphore>>>,
190198
fronter: &Arc<DomainFronter>,
191199
data_ops: Vec<BatchOp>,
192200
data_replies: Vec<(usize, oneshot::Sender<Result<TunnelResponse, String>>)>,
193201
) {
194-
let permit = sem.clone().acquire_owned().await.unwrap();
202+
let script_id = fronter.next_script_id();
203+
let sem = sems
204+
.get(&script_id)
205+
.cloned()
206+
.unwrap_or_else(|| Arc::new(Semaphore::new(CONCURRENCY_PER_DEPLOYMENT)));
207+
let permit = sem.acquire_owned().await.unwrap();
195208
let f = fronter.clone();
196209

197210
tokio::spawn(async move {
@@ -201,8 +214,12 @@ async fn fire_batch(
201214

202215
// Bounded-wait: if the batch takes longer than BATCH_TIMEOUT,
203216
// all sessions in this batch get an error and can retry.
204-
let result = tokio::time::timeout(BATCH_TIMEOUT, f.tunnel_batch_request(&data_ops)).await;
205-
tracing::info!("batch: {} ops, rtt={:?}", n_ops, t0.elapsed());
217+
let result = tokio::time::timeout(
218+
BATCH_TIMEOUT,
219+
f.tunnel_batch_request_to(&script_id, &data_ops),
220+
)
221+
.await;
222+
tracing::info!("batch: {} ops → {}, rtt={:?}", n_ops, &script_id[..script_id.len().min(8)], t0.elapsed());
206223

207224
match result {
208225
Ok(Ok(batch_resp)) => {

0 commit comments

Comments
 (0)